Linux offers powerful tools to schedule and automate tasks. These
tools help administrators automate repetitive tasks, ensuring
consistency and saving time. Below are the most commonly used task
automation tools:
-
cron: Cron is a time-based job scheduler that
automates recurring tasks. It uses a configuration file called the
"crontab" to define tasks and their schedules. Cron jobs are ideal
for tasks that need to run at regular intervals, such as daily
backups or system updates.
Crontab Syntax: Cron jobs are defined using a
five-field format:
* * * * * /path/to/command
| | | | |
| | | | +--- Day of the week (0 - 7, Sunday is 0 or 7)
| | | +----- Month (1 - 12)
| | +------- Day of the month (1 - 31)
| +--------- Hour (0 - 23)
+----------- Minute (0 - 59)
Example 1: Schedule a daily backup at midnight:
0 0 * * * /path/to/backup.sh
Example 2: Run a script every Monday at 8:00 AM:
0 8 * * 1 /path/to/script.sh
Learn more about cron syntax at the
Crontab Man Page.
-
crontab: The `crontab` command is used to manage
cron jobs for individual users. Each user has their own crontab
file, which can be edited using the `crontab -e` command.
Common Crontab Commands:
-
crontab -e
- Edit the current user's crontab file.
-
crontab -l
- List all cron jobs for the current
user.
-
crontab -r
- Remove all cron jobs for the current
user.
Example: Add a cron job to clean temporary files
every Sunday at 2:00 AM:
0 2 * * 0 rm -rf /tmp/*
-
at: The `at` command is used to schedule one-time
tasks. Unlike cron, which is used for recurring tasks, `at` is ideal
for tasks that need to run only once at a specific time.
Usage: To schedule a task, use the `at` command
followed by the desired time. After entering the command, type the
task you want to execute and press Ctrl+D
to save and
exit.
Example 1: Schedule a script to run at 10:00 AM
tomorrow:
at 10:00 AM tomorrow
/path/to/script.sh
Ctrl+D
Example 2: Schedule a system reboot at midnight:
at midnight
reboot
Ctrl+D
Common Commands:
atq
- View the list of pending jobs.
-
atrm [job_id]
- Remove a scheduled job by its ID.
Learn more about the at
command at the
At Man Page.
-
systemd timers: A modern alternative to cron,
`systemd timers` provide event-based scheduling and better
integration with the `systemd` ecosystem. Timers are defined in
`.timer` files and are often paired with `.service` files to execute
tasks.
Example: Create a timer to run a script every 15
minutes:
# /etc/systemd/system/mytask.service
[Unit]
Description=Run my script
[Service]
ExecStart=/path/to/script.sh
# /etc/systemd/system/mytask.timer
[Unit]
Description=Run my script every 15 minutes
[Timer]
OnBootSec=5min
OnUnitActiveSec=15min
[Install]
WantedBy=timers.target
Enable and start the timer:
sudo systemctl enable mytask.timer
sudo systemctl start mytask.timer
Learn more about systemd timers at the
Systemd Timer Documentation.