How to Schedule a Command on Particular Time in Linux

Here’s how to use the at command in Linux to schedule a one-time task for execution at a specific time.

Alby Andersen

The at command in Linux is used to schedule a one-time task to be executed at a specific time or later. It’s useful for running commands or scripts in the future without needing to keep a terminal open. Tasks scheduled with at are executed once at the specified time.


1. Install at (if not already installed)

Most Linux systems have at preinstalled. If not, install it using your package manager:

sudo apt install at   # Debian/Ubuntu
sudo dnf install at   # Fedora/CentOS
sudo pacman -S at     # Arch/Manjaro

2. Basic Syntax

at [time]

After running this command, you’ll enter an interactive prompt where you can type the commands to execute.
Press Ctrl+D to save and exit.


3. Schedule a Task

Example 1: Run a command at 10:00 PM

at 10:00 PM
at> echo "System update started" | mail -s "Update Alert" [email protected]
at> sudo apt update
at> Ctrl+D  # Save and exit

Output:

job 1 at Tue Oct 24 22:00:00 2023

Example 2: Run a script in 2 hours

at now + 2 hours
at> /path/to/backup_script.sh
at> Ctrl+D

4. Time Formats

The at command supports flexible time specifications:

  • Absolute time:
    10:00 PM, 23:45, 2023-12-31, midnight, noon.
  • Relative time:
    now + 30 minutes, tomorrow, next week, next monday.

5. List Pending Jobs

atq

Output:

1       Tue Oct 24 22:00:00 2023 a user
2       Wed Oct 25 14:30:00 2023 a user

6. Remove a Scheduled Job

atrm [job_number]

Example:

atrm 1  # Deletes job 1

7. Advanced Usage

Redirect output to a file:

at now + 1 hour
at> ls -l /var/log > log_list.txt
at> Ctrl+D

Specify a different shell:

at -t 202310241800 -b /bin/zsh
at> echo "Running in Zsh" >> ~/output.log
at> Ctrl+D

Run as root:

sudo at 11:00 PM
at> systemctl restart nginx
at> Ctrl+D

8. Verify the atd Service

Ensure the atd daemon is running to execute scheduled jobs:

systemctl status atd   # Check status
sudo systemctl start atd  # Start if inactive

Important Notes:

  • Permissions: Users must be listed in /etc/at.allow (or not in /etc/at.deny).
  • Logs: Check /var/mail/[user] for command output (if not redirected).
  • Limitations: Jobs are one-time (use cron for recurring tasks).

Notes:

  • at commands execute only once at the given time.
  • Make sure the atd daemon is running; otherwise, at will not work.
  • at is more suitable for tasks that need to be scheduled only once, whereas cron is more appropriate for recurring tasks.

Common Use Cases:

  • Schedule system updates during off-peak hours.
  • Send automated reminders.
  • Run backups at a specific time.
Share This Article