Quick guide to cron in Ubuntu 12.04

Here are some basic concepts on how to set cron jobs in Ubuntu 12.04.

1. The crontab

The crontab is the file that contain entries for each scheduled job, more information at Ubuntu’s Cron How To.

In order to edit the current user’s crontab use:

$ crontab -e

To edit the root’s crontab:

$ sudo crontab -e

In this case we will edit the user’s crontab. To set up a quick test, add the following line at the end of the crontab (as a safety meassure, make sure that there is an empty line at the end of the crontab, as explained in reasons why crontab doesn’t work):

* * * * * touch /tmp/test.txt

This should, the first time it runs, create an empty file called test.txt in your /tmp directory and then refresh its modified timestamp every minute.

2. Cron logs

If things don’t work, there are two good ways to help identify the problem. First, make sure that logging for cron is enabled. In Ubuntu 12.04 you need to make sure the following line is uncommented in /etc/rsyslog.d/50-default.conf.

cron.*      /var/log/cron.log

This sends all cron logging to /var/log/cron.log, which you can then inspect to ensure that you cron is running:

$ tail -f /var/log/cron.log

For this to take effect, you need to restart the syslog service:

$ sudo service rsyslog restart

3. Running a bash script from cron

If this works, we can now create a simple test bash script. A good place to put user scripts is /usr/local/bin, scripts meant to be run as root can be placed in /usr/local/sbin:

$ vim /usr/local/bin/test.sh

Add the following to your file:

#! /usr/bin/env bash
touch /tmp/testing2.txt

Modify your crontab entry:

$ crontab -e
* * * * * /usr/local/bin/test.sh

Did that work?

$ ls /tmp
testing2.txt

If not, try making your script executable and ensure that the owner and group of the script are correct. Assuming that the user and user group are toto:

$ ls -l /usr/local/bin/test.sh
-rw-r--r-- 1 root root 45 Sep 28 12:25 /usr/local/bin/test.sh
$ sudo chmod u+x /usr/local/bin/test.sh && sudo chown toto:toto /usr/local/bin/test.sh
$ ls -l /usr/local/bin/test.sh
-rw-r--r-- 1 toto toto 45 Sep 28 12:27 /usr/local/bin/test.sh

If you need further debugging (your crontab is running and it is calling your script but nothing seems to happen), you can send the output of your script to a temp file. Make sure your crontab entry looks like this:

* * * * * /usr/local/bin/test.sh >/tmp/cron_output.txt 2>&1

Later, if you wish, your script’s output can be discarded:

* * * * * /usr/local/bin/test.sh >/dev/null 2>&1

This, hopefully, should be enough to get you going with a basic cron setup.

Leave a Reply

Your email address will not be published. Required fields are marked *