Computer scienceSystem administration and DevOpsCommand lineTasks automation

Scheduling tasks with cron

10 minutes read

We often need to perform the same tasks at regular intervals. For example, you might check for system updates daily or run a program that removes temporary files from your computer weekly to free up space. Wouldn't it be great if we could automate these tasks and let our computer handle them? This would save us time that we could spend on more creative and enjoyable activities! The cron utility in Linux is the perfect solution for automating repetitive tasks. It's especially helpful for system administrators who need to perform many recurring tasks as frequently as every hour. While Linux also has the at utility for scheduling one-time jobs, in this article, we'll focus on the cron utility.

Cron

Cron is a Linux software utility used to run cronjobs periodically. A cronjob is a task we want to run periodically at fixed time intervals. This task could be a single bash command or it could be a list of bash commands put together in a file.

We need to give cron the details about which cronjob to run and when to run it. These details are mentioned in a cron table (crontab). Each user has their own crontab at /var/spool/cron which contains a list of all the scheduled cronjobs. There are also some system-wide crontab files present at /etc/crontab and /etc/cron.d which can only be edited by the root user.

Listing current user's cronjobs

There is no command called "cron" in Linux. Cron is actually a daemon that examines crontab files and executes the cronjobs mentioned in those files. The command to interact with the cron utility is crontab.

A daemon is a service/process which runs in the background without interacting with the user.

If we try to read the current user's crontab file by going to /var/spool/cron and using the cat command or some editor like vi, we will get a "Permission Denied" error. Though these are files at /var/spool/cron/crontabs, they are not intended to be edited directly.

To see the list of all the cronjobs for the current user, you should use the following command:

crontab -l

If you run this command right now, you might not see any results since we haven't scheduled any cronjobs yet. Go to the next section to learn how to schedule a cronjob.

Scheduling your first cronjob

To schedule a cronjob, you need to mention it in the crontab file. Since editing the crontab file directly by opening /var/spool/cron/crontabs is not allowed, there is another command you need to use to edit a crontab:

crontab -e

This command opens the crontab file for the current user. It is like a normal text file and it will be opened in your default text editor. You can now add your cronjob as an entry to this file. Cronjobs can be added to a crontab file using a fixed syntax as follows:

# ┌───────────── minute (0 - 59)
# │ ┌───────────── hour (0 - 23)
# │ │ ┌───────────── day of the month (1 - 31)
# │ │ │ ┌───────────── month (1 - 12)
# │ │ │ │ ┌───────────── day of the week (0 - 6) (Sunday to Saturday;
# │ │ │ │ │                                   7 is also Sunday on some systems)
# │ │ │ │ │
# │ │ │ │ │
# * * * * * <command to execute>

The first set of parameters is for scheduling the date and time. They can take the values given above. If you are having trouble figuring out the date-time syntax, you can use an online tool like this one to help you. The next parameter is the cronjob, i.e. the command you want to execute periodically. As mentioned earlier, this could be a single bash command or a bash script file.

Once you save and close the crontab file, the cron daemon will automatically execute your cronjob at the specified time.

Cronjob examples

Let's take a look at a basic example of adding a cronjob to a crontab. Open the crontab file by the crontab -e command and add the following line to it:

* * * * * echo "This is fun!" >> /home/user/my_output.txt

This cronjob contains only a single bash command, and it runs this echo command every minute of each day for the whole year. By default, if the cronjob prints any output, it is emailed to the Linux user's email address. If you'd like the output to go to a certain file, you can use the redirection operator >>. So, if we check the my_output.txt file two minutes after the cronjob starts running, we will see the following:

This is fun!
This is fun!

Let's study another example of a cronjob:

0 0 * * 6 /home/user/scripts/create_backup.sh >> /home/usr/logs/backup_log.txt

The above cronjob runs at midnight every Saturday. It executes a bash script called create_backup.sh and stores the output in backup_log.txt.

Special characters

You can use the following special characters in your crontab command:

Special Character

Purpose

Example

asterisk (*)

Match all possible values for the field

0 18 * * * echo 'This runs every day at 6 pm'

comma (,)

Specify multiple values for the field separated by commas

0 18 1,15 * * echo 'This runs on the 1st and 15th day of every month at 6 pm'

hyphen (-)

Specify a range of values for a field

0 18 * * 1-5 echo 'This runs on Monday to Friday of every week at 6 pm'

Uses

The cron utility is used extensively in the IT industry for tasks like the ones listed below:

  • Periodic backups

  • Monitoring disk space

  • Deleting temporary files and log files which are no longer required

  • Generating periodic reports and emailing them

  • Automating repetitive administrative and system maintenance tasks

Conclusion

In this topic, we've learned how to use the cron utility to automate tasks. We've learned what a cronjob is, how to schedule it, and the syntax of a crontab file. Here is a quick summary of the two crontab flags we saw:

crontab -e

Edit your crontab file

crontab -l

Display contents of your crontab file i.e. display the list of your cronjobs

We hope this utility will help you save a lot of time! Now, let's move on to the tasks.

83 learners liked this piece of theory. 1 didn't like it. What about you?
Report a typo