We will learn how to schedule tasks using the cron utility, and in last, we will also discuss some of the online tools which help us with formatting and testing the cron commands.
Origin
Crontab stands for “cron table“. The word cron has been taken from the Greek word Chronos meaning time. Crontab is a system daemon process that will automatically perform some tasks and jobs as per the scheduled time.
Use cases
Crontab is useful to perform various operations such as handling automated backup, rotating log files, syncing files between remote machines and clearing out temporary folders, etc. Crontab can be used for any kind of work, but it becomes especially useful when we start dealing with system administration type of work. Using cron, an administrator can schedule a job to run on a specific time and day. So let’s see how we can set this up.
Crontab Syntax
To execute a list of commands, cron utility reads the configuration files. To interpret the lines in the crontab configuration tables, it follows a Crontab syntax. Crontab has six fields, and the first five(1-5) fields define the date and time of execution. The last field, i.e., 6th field, could be a username and/or task /job/command/script to be executed. * * * * * USER_NAME COMMAND/SCRIPT-TO-EXECUTE │ │ │ │ ││ │ │ │ ││ │ │ │ |_________ Day of Week (0 – 6) (0 is Sunday, or use names)│ │ │ |____________ Month (1 – 12),* means every month│ │ |______________ Day of Month (1 – 31),* means every day│ |________________ Hour (0 – 23),* means every hour|___________________ Minute (0 – 59), * means every minute Notes:
Asterisk (*) is used for matching all possible values for a field. For instance, an asterisk used in the hour field would be equivalent to every hour or an asterisk in the month field would be equivalent to every month. username is optional(available only if it is the system crontab file)
Examples:
Let’s understand the above syntax with some examples
- Schedule a cron to execute at 5 AM daily
- Schedule a cron to execute twice a day at 6 AM and 6 PM
- Schedule a cron to execute on every minute
- Schedule a cron to execute on every Monday at 7 PM.
- Schedule a cron to execute every 15 minutes.
- Schedule a cron to execute on selected months
- Run the shell script /home/script/backup.sh on March 4 at 7:25 A.M
- Schedule a cron to execute every 30 Seconds Since we do not have control over seconds in the Crontab, but we can achieve it through the below two-step process.
Let’s first schedule a task that runs every minute.
Now let’s use sleep command to pause the execution for 30 seconds.
The above task will stop the execution for 30 seconds, and it will resume again.
Type of Cron configuration files
There are two types of Cron configuration files: The UNIX/Linux System Crontab This requires root privilege because usually it is used for system services and critical jobs. The sixth field (in the above syntax description) is the name of a user for the command to run as. It gives the ability to system crontab to run commands as any user. The User Crontab User can also install their own cron jobs using the crontab command. Here also, the sixth field(in the above syntax description) is the command to run, and all commands run as the user who created the crontab. Each user can have their own crontab file, and though these are files in /var/spool/cron/crontabs, they are not intended to be edited directly. We need to use crontab command for editing or setting up our own cron jobs.
How does it work?
The cron service (daemon) runs in the background and constantly checks(every minute) the /etc/crontab file, and /etc/cron.*/ directories. It also checks the /var/spool/cron/ directory. Commands are executed by cron when the minute, hour, and month fields match the current time, and at least one of the two-day fields (day of the month, or day of the week) match the current day.
Basic Commands
Listing out Existing Cron Jobs
We can list out all the Cron jobs without opening the crontab configuration file using below command If there is no existing job it will return the output as If the user has already added some of the jobs it will display as follows.
List Cron for Particular user
To list scheduled jobs of another user, use option as -u (User) and -l (List). crontab -u another_username -l Example: crontab -u geekflare -l
Add/Modify Crontab Entries
To edit the crontab entry, we can use -e option as shown below. crontab -e The above command will open vi editors where you specify the details of the job and save the file. Once saved, you can verify if cron is configured or not with crontab -l.
Add/Modify Crontab Entries for Particular User
We can edit the crontab for another user using below command Example: crontab -u geekflare -e
Remove Crontab Entry
Use -r parameter with Crontab to remove complete scheduled jobs without confirmation from crontab crontab -r If you want confirmation before deleting scheduled jobs, use -i option with -r, which will prompt confirmation from the user before deleting the user’s crontab.
Crontab Special String
Other than the above syntax we discussed, we can also use eight special strings provided by Crontab. It will not only save us time but will also improve readability.
Crontab Special String Examples
- Crontab to schedule tasks on a yearly basis @yearly /scripts/greeting.sh We can execute the above one for sending a new year greeting, It will execute at the first minute of every year.
- Crontab to schedule tasks to execute on a monthly basis. @monthly /scripts/cleanup.sh We can execute the above one to perform some cleanup activities at the beginning of every month. Similarly, we can use other Crontab special string for weekly, daily, and hourly purposes.
Cron Directory
The system administrator can use a system-wide cron schedule which comes under the predefine cron directory as shown below
/etc/cron.d /etc/cron.daily /etc/cron.hourly /etc/cron.monthly /etc/cron.weekly
Crontab Realtime Examples
Let’s discuss some of the real-time examples, that a system administrator or IT professionals usually use.
Delete empty files and directory
45 0 * * * geekflare find /tmp -type f -empty -delete Above cron expression will find the empty files and directory from /tmp directory and it will delete them. This job will run at 12.45 AM on a daily basis. We need to mention the user name to perform this job. In the above example, geekflare user is performing cron job operation.
Execute multiple tasks using a single cron
- /home/scripts/backup.sh; /home/scripts/scritp.sh Multiple tasks/jobs can be separated using a semicolon(;) and can be assigned to a single cron expression.
Cron formatting & testing tools
So far we discussed commands and syntax of crontab to schedule a task. But what if you are not a system administrator and your job is not to set up Cron regularly, it might not be possible to remember the syntax and it opens up the room for error. Don’t worry we have a solution to this problem. There are several Cron formatting tools available online.
# 1. Cron Job Generator
Cron Job Generator is a very user-friendly GUI where you can specify the minute, days, and path of the script to generate crontab. Let’s take a real-time example where I have to execute /home/processMonitor.sh at every 5 minutes between Monday to Friday. So, I got the below Cron syntax which I can put in my crontab by executing crontab –e0,5,10,15,20,25,30,35,40,45,50,55 * * * 1-5 /home/processMonitor.sh
# 2. Crontab Generator
Crontab Generator is another handy tool to generate crontab and with this tool, you can also add if you want to save cron output to the file or send it to email.
# 3. Crontab Guru
Crontab Guru is a simple online cron schedule expression editor. In addition, it provides a useful means of monitoring your cronjob. All we need to do is copy a command provided and append at the end of the crontab definition. In case cron job fails or doesn’t even start, you will receive an alert email. In the below example, Job will execute at 04:05, every day, every month and every week.
# 4. CRON Tester
CRON Tester allows us to test the cron time/date definitions. There might be a situation where we have to decode the existing cron syntax for troubleshooting or just want to do a test. To do so, we can use this tool. All we need to do is copy and paste our cron expression in the cron definition field, then choose the number of iterations and click on Test to see the various dates on which it will run. Let’s check one of our cron expressions 4 3 */2 * *which should run at 03:04(AM) on every two days. Let’s verify it with cron tester.
Conclusion
I hope the above helps you to get a better understanding of Crontab and setting up cron jobs. Scheduling jobs through Cron is one of the many tasks performed by Linux Admin. If you are interested in learning advanced skills then check out this course.