This topic describes the basic concepts and syntax of cron and provides common cron expressions and usage scenarios. This topic helps you fully understand the working mechanism of cron and learn how to create, manage, and debug cron jobs.
Basic principles and components of cron
What is cron?
Cron is a program used to execute jobs on schedule in Linux and Unix operating systems. Cron allows you to automatically run scripts, commands, or software on schedule. Cron is suitable for tasks that need to be performed on a regular basis, such as data backups and system updates.
Working mechanism of cron
Cron runs based on a crontab (cron table) file, which is a configuration file that contains a series of commands and the execution schedules of the commands. Each account can have their own crontab file in their home directory. The system-level crontab file is used for jobs executed at the administrator level.
The cron daemon periodically checks the crontab files, parses the schedules and commands defined in the files, and runs the commands on schedule.
Cron components
Cron daemon: This is a resident background program responsible for regularly checking, scheduling, and executing jobs specified in crontab files.
crontab files:
Account-level crontab files: Each account can edit their own cron jobs in the account-level crontab file by running the
crontab -ecommand. The jobs are valid only for the current account.System-level crontab file: is stored in the
/etc/crontabdirectory. In most cases, the system-level crontab file is managed by a system administrator and used to execute system-level jobs.
crontab syntax: Each line in a crontab file consists of six fields that represent the minutes, hours, day of the month, month, day of the week, and command to run.
Cron expression
To help you better understand how cron works, the following sample code provides an example of a simple crontab file:
# .---------------- minute
# | .------------- hour
# | | .---------- day of month
# | | | .------- month
# | | | | .---- day of week (Sunday=0 or 7)
# | | | | |
# * * * * * user-name command to be run // Specify the path of the command or script that the cron job runs.
30 04 * * * root /path/to/daily_backup.shIn this example, the job configuration indicates that the system runs the daily_backup.sh script as the root user at 04:30 every day.
Make sure that you specify absolute paths for all command instructions or script files.
Valid values of fields
The following table describes the valid ranges and special characters supported by the fields used to define a schedule in cron expressions.
Field | Required | Valid range | Supported special character |
Minutes | Yes | [0, 59] |
|
Hours | Yes | [0, 23] |
|
Day-of-month | Yes | [1, 31] |
|
Month | Yes | [1, 12] or [JAN, DEC] |
|
Day-of-week | Yes | [0, 6], where 0 represents Sunday and 6 represents Saturday. 7 can also respresent Sunday. |
|
Meanings and examples of special characters
Special character | Meaning | Example |
| Includes all values. |
|
| Specifies a range. |
|
| Specifies an interval. |
|
| Specifies an arbitrary value and can be used only in the Day-of-month and Day-of-week fields. |
|
| Can be used in the Day-of-month or Day-of-week field to specify the last day of the month or week. |
|
| Can be used only in the Day-of-month field to specify the weekday that is closest to a specific date. |
|
| Can be used in the Day-of-week field to specify a day of the week and a week of the month. |
|
If you specify the L character in a cron expression, do not specify a list or a range in the expression. If you specify both the L character and a list or a range in a cron expression, a parsing error or logical conflict may occur.
Common cron expressions
Cron expression | Meaning | Scenario |
| Execute the cron job every minute. | Test and check whether cron configurations are activated and executed as expected. |
| Execute the cron job at 00:00 every day. | Reset or back up server data on a daily basis to ensure data security. |
| Execute the cron job at 02:00 every day. | |
| Execute the cron job at 01:00 every day. | |
| Execute the cron job at 06:00 every day. | Update data reports every morning for team members to view the latest information. |
| Execute the cron job at 12:00 every day. | Synchronize data or send daily reminder emails in the enterprise at noon. |
| Execute the cron job at 18:00 from Monday to Friday every week. | Back up data before the end of each business day to ensure that all data of the current day is saved. |
| Execute the cron job at 21:00 every day. | Clean up the business system or back up the transaction data of the current day after the end of commercial operations. |
| Execute the cron job at 00:00 on the first day of each month. | Generate financial, sales, or other business reports at the beginning of each month. |
| Execute the cron job on January 1 and July 1 of each year. | Execute important jobs, such as archiving semi-annual data or restructuring organizations. |
| Execute the cron job at 14:15 on the first day of each month. | Monitor and update security patches for IT systems to ensure system security. |
| Execute the cron job at 00:00 each Sunday. | Clean up and optimize data over the weekend to prepare a clean environment for the new week. |
| Execute the cron job on January 1 of each year. | Automate important annual startup scripts at the beginning of each year, such as to reset the system or archive important data. |
| Execute the cron job every 10 minutes. | Continuously monitor critical systems or services to ensure performance and reliability. |
For more information about cron, visit https://crontab.guru/.
Comparisons of cron
Comparison of cron among mainstream operating systems
Comparison of basic cron features
Feature | Linux or Unix cron | macOS cron | BSD cron | Windows Task Scheduler
|
Minimum execution interval | 1 minute | 1 minute | 1 minute | 1 minute |
Default path of crontab files | /etc/crontab | /usr/lib/cron/tabs/ | /etc/crontab | N/A |
User-level configurations | Supported | Supported | Supported | N/A |
Comparison of special characters in cron expressions
Special character | Linux or Unix cron | macOS cron | BSD cron | Windows Task Scheduler |
* (all values) | Supported | Supported | Supported | Supported |
, (a list of values) | Supported | Supported | Supported | Supported |
- (a range) | Supported | Supported | Supported | Supported |
/ (step size) | Supported | Supported | Supported | Supported |
L (last) | Supported by specific distributions | Not supported | Not supported | N/A |
W (weekday) | Supported by specific distributions | Not supported | Not supported | N/A |
# (the Nth weekday) | Supported by specific distributions | Not supported | Not supported | N/A |
? (not specified) | Supported by specific distributions | Not supported | Not supported | N/A |
Comparison of cron features
Feature | Linux or Unix cron | macOS cron | BSD cron | Windows Task Scheduler |
Environment variables | Limited support | Limited support | Limited support | Supported |
Processing of missed tasks | Not automatically processed | Not automatically processed | Not automatically processed | Processing policies configurable |
Logs | syslog | syslog | syslog | Event Viewer |
Second-level scheduling | Not supported | Not supported | Not supported | Supported |
GUI | None | None | None | Provided |
Task dependencies | Not supported | Not supported | Not supported | Supported |
Network Trigger | Not supported | Not supported | Not supported | Supported |
Power management integration | Not supported | Not supported | Not supported | Supported |
Considerations
Linux, Unix, macOS, or BSD:
Properly configure permissions on files to prevent excessive or insufficient permissions.
Take note of the inheritance of environment variables.
We recommend that you use absolute paths.
Windows Task Scheduler:
Provides more trigger options.
Supports finer-grained access control.
Can be integrated with system events.
Cross-platform compatibility:
Take note of the minimum intersection of features between platforms when you compile cross-platform cron jobs.
We recommend that you use the basic time format and do not use special characters.
Use a cross-platform scheduling tool, such as Jenkins.
Comparison of cron among mainstream frameworks
Comparison of basic syntax
Feature | Spring Framework | Quartz | Linux cron | Jenkins | Kubernetes CronJob |
Second-level support | (Optional) Supported | Supported | Not supported | Supported | Not supported |
The Year field | Optional | Supported | Not supported | Supported | Not supported |
Minimum interval | 1 second | 1 second | 1 minute | 1 second | 1 minute |
Time zone | Supported | Supported | System time zone | Supported | Supported |
Comparison of special characters in cron expressions
Special character | Spring Framework | Quartz | Linux cron | Jenkins | Kubernetes CronJob |
* (all values) | Supported | Supported | Supported | Supported | Supported |
, (a list of values) | Supported | Supported | Supported | Supported | Supported |
- (a range) | Supported | Supported | Supported | Supported | Supported |
/ (step size) | Supported | Supported | Supported | Supported | Supported |
? (not specified) | Supported | Supported | Not supported | Supported | Not supported |
L (last) | Supported | Supported | Partially supported | Supported | Not supported |
W (weekday) | Supported | Supported | Partially supported | Supported | Not supported |
# (the Nth) | Supported | Supported | Not supported | Supported | Not supported |
Scenario recommendations
Framework | Scenario |
Spring Framework | - Java project integration Scenarios that require transactions - Deep integration with the Spring ecosystem |
Quartz | - Independent scheduling systems - Scenarios that require fine-grained task control - Complex scheduling requirements |
Linux cron | - Simple system tasks - Standalone environments - Basic scheduling tasks |
Jenkins | - Continuous integration and continuous delivery/deployment (CI/CD) scenarios - Complex workflows - Scenarios that require visual management |
Kubernetes CronJob | - Containerized environments - Cloud-native applications - Scenarios that require high availability and scalability |
Considerations
Suggestions:
Select an appropriate framework based on the project scale.
Consider maintenance costs and team familiarity.
Evaluate performance and reliability requirements.
Compatibility:
Cron expressions may vary based on the framework.
Take note of the compatibility of cron expressions with a framework when you migrate the expressions to the framework.
Take note of the differences in handling the time zone.
Monitoring and maintenance:
Establish a comprehensive monitoring mechanism.
Collect and analyze logs.
Create fault recovery policies.
Use case
Automatically back up a text file in one directory to another directory at 23:00 every night to ensure data continuity and security.
Considerations
Make sure that you specify the correct source and destination directories. In this example,
/path/to/original/file.txtis used as the source directory and/path/to/backup/file_backup.txtis used as the destination directory.Check whether the specified destination directory exists. If the destination directory does not exist, you must first create the directory or add a command used to create the directory to the cron job.
Make sure that your account has permissions to read the source file and write data to the destination directory.
Periodically check backup files and logs to check whether the cron job runs as expected and generates valid backup files.
Procedure
Open a terminal and enter the
crontab -ecommand to edit cron jobs in your account.Add the following line to the crontab file of your account to add a cron job:
0 23 * * * cp /path/to/original/file.txt /path/to/backup/file_backup.txtDescription:
0 23 * * *specifies that the job is executed at 23:00 every day.cp /path/to/original/file.txt /path/to/backup/file_backup.txtspecifies that thefile.txtfile is copied to the destination directory.
Save and close the crontab file.
If you use the nano editor, press
Ctrl+XandYto confirm and save the changes, and then press theEnterkey to close the file.If you use the vi or vim editor, enter
:wqand press theEnterkey to save and close the file.
FAQ
How do I view cron logs?
In most cases, the executions of cron jobs are recorded in system logs. You can check whether cron jobs are triggered based on cron logs. To view cron logs, run the following command:
grep CRON /var/log/syslogThe command output displays all cron-related logs, including job execution records.
How do I resolve the cron job execution timeout issue?
If the execution of a cron job times out, use the following solutions to resolve the issue:
Optimize the command logic to reduce the execution time.
If the cron job can be split, split the job into multiple smaller jobs.
Add the
timeoutcommand to the Command field to change the maximum execution time of the cron job. For example: add the0 5 * * * timeout 300 /path/to/script.shconfiguration to limit the maximum execution time of the job to 300 seconds.
How do I use simple test commands?
Before you configure a complex cron job, use a simple test command to check whether cron jobs can be triggered as expected. For example, run the following command to configure a cron job that writes the current time to a file every minute:
* * * * * date >> /path/to/date_output.txtOpen the date_output.txt file after a few minutes and check whether a new time record is written to the file every minute.
How do I redirect the output and errors to a log file?
Add a redirection configuration to a cron expression to redirect the output and errors to a log file. This way, you can check whether the cron job is executed as expected and view the output and errors that occurred during execution.
30 4 * * * /path/to/your-script.sh > /path/to/logfile.log 2>&1Check the /path/to/logfile.log file to view the output and errors of the cron job during execution.
How do I configure the frequency of a cron job?
Refer to the following suggestions to configure the frequency of a cron job:
To prevent a cron job from affecting system performance, we recommend that you do not specify an excessively high frequency for the job. Specify an appropriate frequency for the cron job based on the characteristics of the job.
Configure the frequency of a cron job based on your business requirements. Simple daily jobs, such as backups, may need to be executed only once every day, while specific monitoring jobs may need to be executed every hour or more frequently.
Consider the system load. Execute resource-intensive jobs during low-load periods.
What operations can I perform to facilitate the troubleshooting of cron issues?
Redirect the output and errors of a cron job to a log file to facilitate issue tracking. Example:
30 4 * * * /path/to/job.sh > /path/to/job.log 2>&1.Configure the cron daemon to send notifications by email when a cron job encounters an exception or generates output. Make sure that the system email settings are correctly configured or explicitly configure email notifications for the cron job.
In most cases, absolute paths are more reliable than relative paths. We recommend that you use absolute paths in cron jobs.
To edit a cron job, run the
crontab -ecommand. To view all cron jobs in your account, run thecrontab -lcommand. You can check whether the cron jobs are correctly configured.
Why is a cron job not executed on schedule?
Causes and solutions:
If an error exists in the cron expression, check the cron expression and correct the error. Make sure that the schedule settings are correct.
If your account does not have sufficient permissions to execute the cron job, grant your account the required permissions to execute the cron job by running the
chmod +x /path/to/script.shcommand.If an environment issue occurs, the cron job may fail to load the complete environment configurations of your account. Make sure that you specify the full path of the command in the cron job or explicitly configure environment variables in the command.
If other issues occur, check cron logs to identify the issues. The location of cron logs varies based on the system configuration. In most cases, cron logs are stored in the
/var/log/crondirectory. If you redirect the output and errors of the cron job to a specific file, view the logs in the file to check whether the cron job is triggered as expected and whether error messages are returned.
How do I ensure that a cron job will take effect?
Check the syntax of the cron expression. Make sure that the time and date syntax is correct. Run the crontab -e command to edit the cron job and check whether all fields are correctly configured. A cron expression includes the following fields:
<Minutes> <Hours> <Day-of-month> <Month> <Day-of-week> <Command>Make sure that each field is correct.
In many Linux operating systems, the cron service can execute jobs only when the service is running. You can run the following command to check the status of the cron service:
sudo service cron statusOr:
sudo systemctl status cron If the cron service is not started, run the following command to start the service:
sudo service cron startOr:
sudo systemctl start cronGrant execution permissions on the script file that you specify in the cron job. Run the following command:
chmod +x /path/to/your-script.shHow do I view all cron jobs in my account?
Run the crontab -l command to view all cron jobs in your account. This is a common command in Linux and Unix. Cron is a time-based job scheduler that allows you to automatically run scripts or commands on schedule.
Take note of the following items:
The preceding command displays only cron jobs in the current account. To view the cron jobs in another account, you must obtain the required system permissions.
If no cron job is configured in your account, the
crontab -lcommand may not display information.
How do I view cron jobs that can be accessed by my account?
To view cron jobs that can be accessed by your account, you can run the crontab -l command. If your account does not have root permissions or permissions to view and edit the cron jobs of other accounts, the preceding command displays only cron jobs that belong to your account. If your account has root permissions or permissions to view and edit the cron jobs of other accounts, you can run the preceding command and specify the username of an account in the command to view all cron jobs that belong to the specified account.
Take note of the following items:
You can use a regular account to view and edit only cron jobs that belong to the account. You can use the root account or an account to which sufficient permissions are granted to view and edit the cron jobs of all accounts.
Commands in cron jobs defined in the crontab file are run in a simplified environment. By default, a number of environment variables may not be loaded. We recommend that you use full paths in the commands.
How do I edit a crontab file to delete a cron job?
Run the
crontab -ecommand to open the crontab file of your account in the default editor. The default editor can beviornano.In the editor, find the line that contains the cron job that you want to delete, and then delete the line. In the
viorvimeditor, move the pointer to the line and pressddto delete the line. In thenanoeditor, move the pointer to the line by using the arrow keys, and then press the Delete key to delete the line or pressCtrl+Kto cut the line.Save and close the crontab file.
In the
viorvimeditor, enter:wqand press the Enter key to save the changes and close the file.In the
nanoeditor, pressCtrl+X, enterYto confirm and save the changes, and then press the Enter key to close the file.
If you want to delete all cron jobs from your account, run the following command.
The command deletes all cron jobs from your account without asking for confirmation. Proceed with caution.
crontab -rTake note of the following items:
Before you edit or delete a cron job, we recommend that you back up your crontab file. You can run the
crontab -l > crontab_backup.txtcommand to back up the cron jobs in your crontab file to another file.When you delete or edit cron jobs in your crontab file, the operating system or applications in the operating system may be affected. Before you delete or edit a cron job, make sure that you are fully aware of the potential impact of the operation.
What do I do if the "You (*) are not allowed to use this program (crontab)" error message appears when I run the crontab command as a non-root user in Linux?
Connect to the Linux ECS instance as the root user.
For more information, see Use Workbench to connect to a Linux instance over SSH.
Run the following commands to check whether the
cron.allowandcron.denyfiles exist:find /etc/cron.allow find /etc/cron.denyThe following table describes the relationship between the existence of the
cron.allowandcron.denyfiles and user permissions to run the crontab command.Whether the cron.allow file exists
Whether the cron.deny file exists
Users who can run the crontab command
No
No
Only the root user can run the crontab command.
Yes
No
Only users who are specified in the cron.allow file can run the crontab command.
No
Yes
Users who are not specified in the cron.deny file can run the crontab command.
NoteIf the cron.deny file is empty, all users can run the crontab command.
Yes
Yes
Only users who are specified in the cron.allow file can run the crontab command.
NoteThe cron.allow file takes precedence over the cron.deny file. In this case, the cron.deny file does not take effect.
Modify the
cron.alloworcron.denyfile based on your business scenario:If the
cron.allowfile does not exist and thecron.denyfile contains the username of the non-root user, delete the username, and then save thecron.denyfile.If the
cron.allowfile exists, add the non-root user to thecron.allowfile, and then save the file.
Run the following command to restart the cron service:
systemctl restart crond.serviceSwitch to the non-root user and run the
crontabcommand again.
What values can I specify for the Day-of-week field in a cron expression and what items must I take note of when I configure the Day-of-week and Day-of-month fields?
The Day-of-week field is the fifth field in a cron expression and is used to specify the days of the week on which you want to execute a cron job.
Valid values in the numeric format: 1 to 7, which correspond to Sunday to Saturday in a week.
Valid values in the abbreviation format: SUN, MON, TUE, WED, THU, FRI, and SAT.
Examples:
MON-FRI: specifies every day from Monday to Friday.MON,WED,FRI: specifies every Monday, Wednesday, and Friday.MON-WED,SAT: specifies days from Monday to Wednesday and Saturday.2-6: specifies days of the week from Monday to Friday. In this example, the Day-of-week field is in the numeric format.SUN,SAT: specifies every weekend, which includes Saturday and Sunday.
Advanced syntax:
SUN#1: specifies the first Sunday of every month.6L: specifies the last Friday of every month.*/2: specifies every other day.MON#2: specifies the second Monday of every month.
When you configure the Day-of-week and Day-of-month fields, take note of the following items:
The abbreviations for the days of the week are not case-sensitive. For example,
MONis equivalent tomon.To prevent the days of the week from conflicting with the days of the month, use
?in the Day-of-week or Day-of-month field.When you use the
Land#characters in a cron expression, make sure that the expression matches valid dates.If you use the numeric format for the Day-of-week field, take note that 1 represents Sunday instead of Monday.
How do I use the L character in the Day-of-month and Day-of-week fields in cron expressions?
In the Day-of-month field
If you use only the L character, take note of the following items:
The
Lcharacter specifies the last day of the month.Example:
0 0 L * ?specifies midnight on the last day of every month.The L character automatically adapts to the number of days in different months, including February in leap years.
If you use the L character together with an offset value, take note of the following items:
The
L-nvalue specifies the day that is one day before the Nth day from the end of the month.Example:
0 0 L-2 * ?specifies midnight on the third day from the end of every month.
In the Day-of-week field
If you use only the L character, take note of the following items:
The
Lcharacter specifies Saturday, which is the last day of the week.Example:
0 0 ? * Lspecifies the midnight every Saturday.
If you use the L character together with a number, take note of the following items:
The
nLvalue specifies the last N of the month, in which N represents a day of the week.Example:
6Lspecifies the last Friday of the month.Example:
2Lspecifies the last Monday of the month.
If you use the L character together with a Day-of-week abbreviation, take note of the following items:
The
XXXLvalue specifies the last specific day of the week in the month.Example:
FRILspecifies the last Friday of the month.Example:
MONLspecifies the last Monday of the month.
Considerations
Do not use the following combination:
The L character and a range or a list
Error examples:
L,15andL-3,15
Day-of-month adaptation:
The L character automatically adapts to the number of days in different months.
The Day-of-month field can correctly handle the case of February in leap years.
Take note of the following items when you use the Day-of-week field:
If you use the L character in the Day-of-week field, we recommend that you set the Day-of-month field to
?.This prevents date conflicts.
Execution time:
If the last day-of-the-week that you specify for a cron job does not exist, the job is not executed.
For example, February may not have a fifth Friday.
What do I do if the "errors in crontab file, can't install" error message appears when I run the crontab -e command on a Linux instance?
To resolve this issue, you can log on to the instance and change the cron expression format in the crontab file or resize the disk on which the file is stored.
Connect to the Linux ECS instance.
For more information, see Methods for connecting to an ECS instance.
Run the following command to query the usage of disk space:
df -hA command output similar to the following one is displayed. The values in the Use% column indicate the space usage of each file system. In this example, the space usage of the /dev/xvda1 partition is 15%.
If the disk usage is close to 100%, the disk space is insufficient. We recommend that you resize the disk before you run the crontab -e command. For information about how to resize a disk, see Overview.

