Cron is used to schedule jobs on a regular basis.
It has the following files and directory:
- /etc/crontab – system crontab file. Root user use it to create automatic task.
- /etc/cron.d – crontab extension directory, contain cron files.
- /etc/cron.daily: – this directory contain scripts, all scripts in the directory run once a day.
- /etc/cron.hourly: – this directory contain scripts, all scripts in the directory run once in an hour.
- /etc/cron.monthly: – this directory contain scripts, all scripts in the directory run once in a month.
- /etc/cron.weekly: – this directory contain scripts, all scripts in the directory run once in a week.
<minute> <hour> <day of month> <month> <day of the week> <user account> <command to run>
* * * * * root ls /etc
will run “
ls /etc” as a root user every minute.
0 6 * * 1-5 root ls /var
will run at 6Am from Monday to Friday (day start from 0=sunday).
We can also use shortcut:
@hourly root ls /proc
will run every hour “
ls /proc“, useful when we only want it to happen once a day and we don’t care exactly when.The other macros are @daily, @monthly, @yearly
if we want to see the cron jobs for our user:
if we are root user:
crontab -l -u
will show the cron job for <user>
if we want to edit, remove or add cron job to our user:
will open text editor for the crontab file for our user. When we edit crontab file, then we should skip the “user” column, we only need the command, and the specific interval.
Nice trick that we can do to run cron in interval less than 1 minutes is to use the sleep command.The sleep command get as a parameter a number of second, and wait until this second pass.
So if we want to have command to run every 30 minutes:
* * * * * <command> * * * * * sleep 30; <command>