cron is a software utility used in Unix-like operating systems to schedule automatic recurring tasks or jobs.
Specifically, cron is a daemon (a type of background process that runs continuously) that executes scheduled commands or scripts at specified intervals. It is typically included in the system’s standard utilities or coreutils package, which is separate from the kernel.
The cron daemon (crond) runs in the background and checks for scheduled jobs every minute.
The crontab (cron table) is a file that contains a list of commands meant to be run at specified times. Each user can have their own crontab file.
The syntax for a crontab entry is:
* * * * * command_to_run
The five asterisks represent:
* - Every value (e.g., every minute, every hour)., - Multiple values (e.g., 1,2,3).- - Range of values (e.g., 1-5 for Monday to Friday)./ - Step values (e.g., */15 for every 15 minutes).To view your crontab:
crontab -l
To edit your crontab:
crontab -e
Run a script every day at 2 AM:
0 2 * * * /path/to/script.sh
Run a command every 5 minutes:
*/5 * * * * /path/to/command
Run a backup script every Sunday at 3 AM:
0 3 * * 0 /path/to/backup.sh
To log output from a cron job, you can redirect output to a file:
0 2 * * * /path/to/script.sh >> /path/to/logfile.log 2>&1
This command appends both standard output and error output to logfile.log.
chmod +x /path/to/script.sh).Start the cron service:
sudo service cron start
Stop the cron service:
sudo service cron stop
Restart the cron service:
sudo service cron restart
You can set environment variables in your crontab file:
SHELL=/bin/bash
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
This ensures that your cron jobs have the correct environment.
Cron supports several predefined scheduling keywords:
@reboot - Run once, at startup.@yearly or @annually - Run once a year, i.e., 0 0 1 1 *.@monthly - Run once a month, i.e., 0 0 1 * *.@weekly - Run once a week, i.e., 0 0 * * 0.@daily or @midnight - Run once a day, i.e., 0 0 * * *.@hourly - Run once an hour, i.e., 0 * * * *.Example:
@daily /path/to/daily-script.sh
If your cron job isn’t running as expected, check the following:
For systems that are not always running, consider using anacron. It ensures that scheduled jobs are run even if the system was off at the scheduled time.
For more advanced scheduling options, you might want to explore additional features or tools like anacron, which handles tasks that are supposed to run on a schedule but may not if the system is off.