Cron tasks

Cron is a daemon that will execute tasks periodically.

Cron will only executed jobs when the system is online! If the system is offline when a job is scheduled the job is not executed (obviously), but cron won't ever catch up on missed jobs. For a desktop computer or other systems that aren't always online, consider using anacron instead.

Managing cron tasks

Cron tasks are defined in a file named crontab. One exist for every user. See man 5 crontab for more information.

In order to delete a user's crontab (this will delete every job), run crontab -r as that user.

Getting output

Cron jobs output is sent as mail to the user who runs them. Run mail to read it. (p to print, d to delete, h to list, q to quit). In the crontab you can change the user who receives mail for the following commands by setting the MAILTO variable.

Mail to root may not be sent directly to it, but sent to user 'mail' instead. Run mail -u mail to get it. To check if you have new mail you can check the non-emptyness of /var/spool/mail/mail file. (if [ -s /var/spool/mail/mail ] ; then echo You have mail ; fi).

Anacron

Anacron allow to schedule jobs with a certain frequency. When it is run, it checks when the job was last executed (it saves the last executed time for every job in /var/spool/anacron). If jobs needs to be executed to maintain the frequency, they will be.

Anacron doesn't support running jobs hourly, but cron can do it (specify @hourly as job time), which normally is enough since very often a device will run for at least an hour.

Anacron as root

If anacron is installed, you just need to edit its configuration file to add jobs that will be executed as root. See man anacrontab.

Anacron as user

(Information taken from here and here)

Anacron doesn't natively support running jobs as a non-root user (the configuration file is root-only editable), but we can make it do so with cron. The idea is to create a anacrontab file and spool directory in the user home directory, and use cron to execute anacron every hour.

For a simple setup just add a line like this to your crontab: @hourly /usr/sbin/anacron -s -t {anacrontab file} -S {spool directory} and then insert jobs in the anacrontab. Here we will do a nicer setup, which ease the addition of new jobs.

Note: in the anacrontab we use find to find all the executable programs in the subfolders. Some examples would use run-parts, but that program ignores silently files with an extension, so e.g. script.sh won't be executed. This is explained here.

To add a new job

Either copy or symlink the program/script in the directory based on the frequency you want the program tu run at. Make sure that the program is executable.