Similar to the "at" command, Cronjobs allow you to schedule certain tasks that you'd like to to complete automatically at a specified time. The "at" command, however, is rather limited; it typically only works for the time of the current day that you set it on. It doesn't allow you to continually apply the job on certain days/times/months of the year. Instead, we will use another tool to accomplish this: Cron.
The Cron utility is built into most Linux distributions and functions as a sort of scheduler. You can schedule a script to run at a certain minute of a certain day, 2 days a week for example. Note that Cron does follow a fairly strict syntax that we will go over shortly.
Setting up
First, open up a terminal session and input the following command:
crontab -e
You should be greeted with the following screen:
This is where we will insert our cronjobs to run scripts at designated times and days.
Syntax
The syntax of a cronjob is as follows:
A B C D E /some/directory/script.sh output
A - minute of the hour
B - hour of the day
C - day of the month
D - month of the year
E - day of the week
The letters in the template mentioned above will be replaced with numbers, the range of numbers varying depending on the category. For example, the range of numbers for A would be 0-59 while the range of numbers for B would be 0-23. The range of numbers for C would be 0-31 and so on. Note that a cronjob typically sends output to the email of crontab file when it runs. We can suppress that output by appending
>/dev/null 2>&1
to the end of the line of every cronjob that we specify.
Examples
Before we list some examples, it is important to understand what the * character does for cronjobs. The * character functions as a "wildcard" character. Instead of specifying a certain timeslot, the * character specifies that the job will happen for every value available in that timeslot. We will show with some examples.
The following command will run ~/script.sh at 0030 on the first day of the month, for every month, any day of the week:
30 0 1 * * ~/script.sh >/dev/null 2>&1
The following command will run ~/script.sh at the half-hour, every hour, of every day, of every day of the week:
30 * * * * ~/script.sh >/dev/null 2>&1
Additionally, I can use the character / to specify that I would like the command to be executed in intervals. For example, the following command will execute every 30 minutes:
*/30 * * * * ~/script.sh >/dev/null 2>&1
The following cronjob will execute every other day:
* * */2 * * ~/script.sh >dev/null 2>&1
The following cronjob will execute every other month, and when it is those months, it will execute every other day:
* * */2 */2 * ~/script.sh >/dev/null 2>&1
We can see that cronjobs have infinite potential to automate tedious tasks that could be prone to human error, opening a gateway toward a much more efficient Linux working environment.
Comments
0 comments
Please sign in to leave a comment.