How to Set Up a Cron Job in Linux?
Introduction
Many of us enjoy using smart reminder apps that eliminate the need to worry about unfinished tasks. A cron job is a similar tool, where the term “job” refers to tasks or commands. By setting up a cron job in Linux, you can ensure the smooth execution of repetitive tasks without having to worry about system maintenance, backups, updates, and more.
This feature makes it easy to schedule essential tasks at specific intervals, and it’s known to reduce the need for manual intervention. Did you know that a crontab setup in Linux can assist you in automating your workflow?
In this article, we will uncover various aspects of crontab syntax. Moreover, we will guide you to set up a cron job in Linux and edit a crontab. This article also contains examples of cron jobs. So, let’s start the reading process without wasting any more time.
Basic Crontab Syntax
It’s important to know that crontab and cron job are two distinct things before diving deeper into crontab syntax in Linux. A crontab is used to edit a cron job appearing on it in the form of a crontab entry, which is a line containing the details of a particular task’s schedule. It’s worth noting that a crontab can have several crontab entries. When we discuss crontab syntax in Linux, we’re referring to the structure in which a crontab entry should be composed. A basic crontab syntax consists of five fields. Have a look at the below syntax.
* * * * *
or
a b c d e /directory/command output
Each of the above fields, "* * * * *" or "a b c d e," represents a unit of time. We will have a careful look at the cron job time format below.
1. Cron Job Time Format
The best thing about the cron job time format is that it offers the
utmost flexibility when it comes to multi-level scheduling. With the
minute, hour, and month features, you can control the tasks
precisely. Check the below details below about the time format.
"a b c d e /directory/command output"
"a" = minute, value is between 0 to 59. Example of syntax:
8* * * *
This syntax means that the job will be repeated every 8th
minute.
"b" = hour, value is between 0 to 23. Example of syntax:
0 8 * * *
This syntax means that the job will be repeated when the hour is
Eight or more specifically, at 8:00 AM.
"c" = day, value is between 0 to 31. Example of syntax:
0 0 8 * *
This syntax means that the cron job will run every eight days of
the month at midnight, as “0 0” suggests the midnight time.
"d" = month, value is between 0 to 7. Example of syntax:
0 0 0 8 *
This syntax is slightly different as it will run the job once a year.
The job will run at midnight in August. The “0”
value in the field of day signifies the 0th day, which is not
possible. Also, the day of the field is “*,” which means that there
is no specification of the day of the week. So, ultimately the job
will run on the 1st of August month once a year.
"e" = day of the week, value is between 0 to 7. Example of syntax:
0 0 * * 7
This syntax means that the job will run every Sunday at
midnight.
2. Command to Execute
Use the “Command to execute” function to run a particular script. Simply enter the
command into the terminal window. Here’s an example to help you understand it better.
Suppose you want to back up a directory every day at 4 AM. You
can use the bellow command to perform the function.
0 4 * * * cp -r /path/to/source /path/to/destination
The “cp” term in the above syntax stands for the copy command.
Further, the word “r” is used for recursive copying, which will
preserve the original structure of the directory.
3. Output
When we run a cron job, the script or command produces an output.
This output which usually contains messages and status updates is
sent to a particular location, which is, by default, the email id of the
cron job owner. Do you know you can alter the location of the
output? Well, not just the location; you can also send the output
to other systems and even discard the output.
- Output can be redirected to a specific file. Suppose you want to send a backup output to a log file; then the following command can be used.
0 2 * * * /path/to/backup_script.sh > /path/to/output.log
As per the above syntax, the cron job output will be sent to
the log file at 02:00 AM. Whereas “path/to/backup_script.sh”
displays the current path of the script. The part “path/to/output.log”
is written to enter the location of the log file where the output is to
be stored.
- If the user wants to discard the output, then the syntax below will be useful.
0 8 * * * /path/to/script.sh > /dev/null 2>&1
In the above syntax,”>” is used to redirect the output, and “dev/null”
the location of the output is a special device file
that discards the input. The “2>&1” part signifies that the error
message is also sent to the same special device file.
4. Using Operators
Operators are simply signs and symbols that enhance the syntax of
any programming language. The aim of operators in cron tab syntax
in Linux is to alter the behavior of the crontab entry to enhance
flexibility. We have listed a few operators below for your convenience.
- Asterisk () operator: This operator indicates any and every.
- Comma (,) operator: It is used to separate multiple values.
- Hyphen (-) operator: This symbol is used to indicate a range of values. Example 2-6 (defining Tuesday to Saturday in a week).
- Slash (/) operator: It indicates an interval within the value.
Setting Up a Cron Job
It is very easy to set up the cron job entry in Linux, even if it is your first time doing so. Execute the mentioned steps to complete the process.
- Open the terminal window and log in as a cron job user.
- Enter the below command to access the cron table of the user.
crontab -e
3. After you have opened the user’s cron table, you need to select an editor if this is your
first time setting up a cron job. The editor may include options like nano, vi, etc.
4. Now, you have to put in the cron job entry in the table through the below command.
* * * * * /path/to/command
The above command means the entry will run every minute. You can replace the
“path/to/command” with the script in this command.
5. You can now customize the entry with time fields and operators.
6. After the editing, you can easily save and exit the entry by using Ctrl+O and Ctrol+X,
respectively, if the editor is nano.
7. The last step includes verification of the entry through the below command.
crontab -l
The above command will showcase all the cron job entries in the
Linux.
How to Edit the Crontab File?
To edit an existing cron job entry in Linux, open your terminal window and log in as the crontab user. Then, enter the command “crontab -e” in the terminal to access the user’s cron table. This will display the existing cron job entries in the table. You can now easily edit or add new entries. Save and exit the file once you complete the required changes. To verify the changes, enter “crontab -l” in the terminal. The changes should be successfully made.
Edit crontab for a Different User
Editing crontab for another user requires sufficient permission. Open the terminal window and log in as the other using the below command.
su - <username>
In the above command, you need to replace the <username> with the actual id. After the login, you will be able to access the user’s crontab file by running the following command.
crontab -e
Now you can easily edit the cron job entries on the tab and then simply save the file. Ensure to verify the editing after you exit the file through the given command.
crontab -l
Cron Job Examples
Examples of cron job entries include various schedules. Take a brief look at some instances to clear the air around the cron job in Linux.
Example 1.
Execute a cron job after every minute without any halt. Use the below syntax.
* * * * * /path/to/command
Example 2.
Run a script at 8:00 AM regularly. Use the below command.
0 8 * * * /path/to/script.sh
Example 3.
Regularly back up a directory every Sunday at midnight. Use the below syntax.
0 0 * * 0 cp -r /path/to/source /path/to/destination
Example 4.
Clean up a temporary file every hour. Follow the below command.
0 * * * * rm -rf /path/to/temp/*
Example 5.
Run a cron job on the 15th day of every month. Use the below syntax.
0 0 15 * * /path/to/command
Using Special Characters
Let us have a quick look at some examples of crontab syntax in Linux using special characters.
Example 1.
Execute a command hourly and set it to run between 9 AM and 5 PM on weekdays from Monday to Friday. Use the below syntax.
0 9-17 * * 1-5 /path/to/command
Example 2.
Execute a script on the 2nd and 22nd day of each month. Use the following syntax.
0 0 2,22 * * /path/to/script.sh
How to List Existing Cron Jobs?
To display the existing cron jobs in Linux, just insert the below command in the terminal window.
crontab –l
Also Read: Syntax of Linux Set Command & How to Use it
Conclusion
If you’re looking to automate tasks in Linux, cron jobs are an incredibly useful tool. With them, you can easily schedule updates and maintenance that require no human intervention. Understanding the crontab syntax in Linux is key to creating and editing cron job entries. This syntax includes time fields like minute, hour, day, month, and day of the week and the command to execute.
Using special characters like asterisks, commas, hyphens, and slashes can help you create flexible schedules that fit your needs. To set up a cron job in Linux, you’ll need to access the cron table using the “crontab -e” command. Then, add your cron job entry with the desired schedule and command to execute. When you are done with the changes, be sure to save them and verify them using the “crontab -l” command. Overall, cron jobs are powerful and efficient tools that make system maintenance and repetitive tasks a breeze.