How to Schedule Tasks Using Cron on Linux and Unix
There are various ways to use the cron to schedule tasks. But the common way involves specifying the date and time. To do this, a specified command is executed. The secret involves utilizing the 5 fields of a crontab command to define which day the command should execute.
Here, the tricks lie in using the special characters and, in particular, the hyphen (-) which gives a list of the values to use for a given field.
The syntax for the crontab is as follows:
Our focus is on the Day-of-week. The allowed values are 0 to 6, where 0 is Sunday and 6 is Saturday. Therefore, to specify a command that runs only on weekdays, we set the Day-of-week to 1-5 with no spaces.
The command would be:
The given syntax specifies no specific time that the command should execute. If you needed to set it to run every weekday at 10:00 AM, the command would be:
Now, add the following command at the bottom of your crontab file by running the command that follows:
Save the file and exit.
You now have a cron job for the current user. If you run a script like in this case, ensure to give its full path.
Other Options to Run a Command on Weekdays
There are various ways to set a command that runs on weekdays. Let’s have some examples:
1. Weekdays of a Given Month
Not every month is a working day. Therefore, you may wish to execute your cron job at a particular month only. For this, you can specify the month by using the month number where 1 represents January. To only run the same command on January at 10:00 AM, change it to reflect the one in the following:
2. Weekdays and Specific Days of a Given Month
Some tasks can be scheduled to run on a given day of a given month, provided it’s a weekday. For instance, you may set a backup script that runs on the 5th day of January on weekdays and at a given time. The command for that would be:
In the previous example, we specified that the named script is to execute at 10:00 AM on the 5th day of January from Monday to Friday.
The bottom line is that you can change the various fields to tweak when the command should execute on weekdays only. You can choose which month it should run or specify a range. Moreover, you can set the exact time or use an interval at a particular hour to match your need.
We covered how you can use the crontab to schedule a job that runs only on weekdays. Furthermore, we learned the other ways that you can play around with the other fields to be more specific on the day of the month, hour, minute, and month that your command should run. Try it out!