How to Setup Your First Cron Job

introduction

Cron jobs are automatic triggers to run a specified program at a specified time. They are helpful for scheduling repetitive tasks. Here is a guide for getting your first one setup.

unix shell commands

crontab -e              # Launch Crontab
i                       # Enter Insert Mode
[Esc]                   # Exit Insert Mode
ZZ                      # Save and Exit Crontab [Use capital Z's here]

an example

Let us say there is a python script, FileMover.py, that should run every day at 7:01 p.m. First, copy FileMover.py into a new cron folder in your Unix home directory. Next, convert Windows-style line endings to Unix-style line endings, if needed.

sed -i 's/\r//' ~/cron/FileMover.py

Be sure to end the python file with an empty new line. Next, using the Unix shell commands above, launch the Crontab. Go to insert mode and add the following new line for the new job:

1 19 * * 1-5 . $HOME/.bashrc; ~cron/FileMover.py

In plain English:

1 minute past 19:00, every day of the month, every month of the year, Monday through Friday, using the .bashrc file from the home directory, run the file located at ~cron/FileMover.py

The .bashrc file should be specified in order to take advantage of any additional installed Python packages.

Finally, exit insert mode, and save and exit the Crontab.

further reading

Cron jobs can be set to run at nearly any interval. For example, to run at 5 minutes past every hour:

5 * * * * FileName.py

or to run once every other hour:

0 */2 * * * FileName.py

The below table is from the article Cron and Crontab commands on softpanorama.org. I also found this guide to be helpful.

Crontab Reference