How to add commands to cron in Linux

The guides on this website often require that commands are run on a regular basis or run when your machine starts up. This is very easily done with the command scheduling tool built into Linux. This is known as cron, or crontab (short for cron table, I believe). The easiest way I’ve found to add things to this is via Webmin as it lets you quickly select a time to run a command and enter the command via a convenient web interface. Here’s an easy guide I wrote previously on how to install Webmin.
Webmin cron editor

However, if you want to do it from the command line then this is how to do it…

First we need to understand how the cron table is structured. If you run crontab -l  you should get a list of the jobs currently scheduled on your system. Note that this will only show you the jobs associated with your currently logged in user.

To see ALL scheduled jobs you should run the following as root:
for user in $(cut -f1 -d: /etc/passwd); do echo $user; crontab -u $user -l; done
You’ll get an output which looks something like this but a bit longer as I’ve chopped mine off so you don’t see all my stuff!:
cronjobs

Notice the start of each line. This series of numbers and *’s will determine when your job runs. These entries can been amended using the following rules:

You can open the /etc/crontab file and edit it directly but that is not best practice as you could make a mistake. To add stuff to cron you should use the command:
crontab -e
Then add your new command using the scheduling rules above in this format…

This would run /path/to/script.sh at 2:15pm on the first of every month. Or adding…

would run /path/to/script.sh every time you started the NAS.

 

Useful sources
http://stackoverflow.com/questions/134906/how-do-i-list-all-cron-jobs-for-all-users
http://stackoverflow.com/questions/878600/how-to-create-cronjob-using-bash
http://stackoverflow.com/questions/5398014/cron-crontab-execute-a-script-every-minute-and-another-one-every-24-hours
http://stackoverflow.com/a/16153767
http://www.thegeekstuff.com/2009/06/15-practical-crontab-examples/
http://www.cyberciti.biz/faq/how-do-i-add-jobs-to-cron-under-linux-or-unix-oses/

Leave a Reply

(email optional)