View Categories

Scheduled tasks (cron jobs) in Linux

2 min read

Table of Contents

You have just finished your new backup script for your server, and you want to run it every day at 00:01. To do this you need to schedule the backup job in Linux using cron.

Log in as the root user and run:

contab -e

If this is the first time you are running it then you will be asked which editor you want to use e.g. nano or vi, the default will be vi and assumed for the rest of this guide.

Cron jobs use the expression to tell them when to run, at first, this can seem confusing as it is made up of 5 positions often represented in guides by asterisks * * * * * these are placeholders for: minute, hour, day(month), month day (week)

So, for example, to run a job daily at 00:01 you would use 1 0 * * * that means 1 minute past 0 hours (midnight) every day of every week every month, if this is tsill confusing check out crontab guru https://crontab.guru/#1_0_*_*_* and check some of the examples or generate your own expression using the interactive tools on the website.

To put this expression together with your backup script, lets say it is located at /backup/backup.sh you would add a line to your crontab that looks like this:

1 0 * * * /backup/backup.sh

If you are using the default editor vi, you first need to press the ‘i’ key, this allowing you to insert text freely. When you are finished, press Esc, then type :wq which is write and quit.

You should not get a message that the crontab has been installed or updated.

Extra tips #

If you have written your shell script and you have not used absolute paths to commands, it may fail as cron jobs are not interpreted as they would be during a regular ssh session, it is worth putting environment variables and location in your script at the start so that commands can be found such as ‘ls’ instead of having to use /bin/usr/ls (the absolute path)

You can achieve this by placing the following at the start of your script:

PATH=/usr/local/bin:/bin:/usr/bin:/usr/local/sbin:/usr/sbin:/sbin

That should cover most essential toolsets and commands for your scripts.

If you do have issues with a job not running as expected you can likely find the reason why in the log file /var/log/cron