The built-in cron process in Linux can help us fulfill these needs. Combined with shell scripts, cron can handle even very complex commands.
cron Introduction
The crontab command we often use is short for cron table. It is the configuration file for cron, also called the job list. We can find the relevant configuration files in the following folders.
- The /var/spool/cron/ directory stores crontab tasks for every user, including root. Each task is named after its creator.
- /etc/crontab This file is responsible for scheduling various administrative and maintenance tasks.
- /etc/cron.d/ This directory is used to store any crontab files or scripts to be executed.
- We can also put scripts in the /etc/cron.hourly, /etc/cron.daily, /etc/cron.weekly, and /etc/cron.monthly directories to run them once per hour, day, week, or month.
Using crontab
The commands we commonly use are as follows:
crontab [-u username] //省略用户表表示操作当前用户的crontab
-e (编辑工作表)
-l (列出工作表里的命令)
-r (删除工作作)
We usecrontab -eEnter the current user's worktable editor, which is the common vim interface. Each line is a command.
The crontab command structure consists of time + action. Its time hasminute, hour, day, month, weekfive types. The operators are:
- * All numbers within the value range
- /Every how many numbers
- -From X to Z
- ,Scattered numbers
Examples
Example 1: Execute myCommand every 1 minute
* * * * * myCommand
Example 2: Execute at the 3rd and 15th minutes of every hour
3,15 * * * * myCommand
Example 3: Execute at the 3rd and 15th minutes between 8 AM and 11 AM
3,15 8-11 * * * myCommand
Example 4: Execute at the 3rd and 15th minutes between 8 AM and 11 AM every two days
3,15 8-11 */2 * * myCommand
Example 5: Execute at the 3rd and 15th minutes between 8 AM and 11 AM every Monday
3,15 8-11 * * 1 myCommand
Example 6: Restart smb at 21:30 every night
30 21 * * * /etc/init.d/smb restart
Example 7: Restart smb at 4:45 on the 1st, 10th, and 22nd of every month
45 4 1,10,22 * * /etc/init.d/smb restart
Example 8: Restart smb at 1:10 every Saturday and Sunday
10 1 * * 6,0 /etc/init.d/smb restart
Example 9: Restart smb every 30 minutes between 18:00 and 23:00 every day
0,30 18-23 * * * /etc/init.d/smb restart
Example 10: Restart smb at 11:00 pm every Saturday
0 23 * * 6 /etc/init.d/smb restart
Example 11: Restart smb every hour
0 */1 * * * /etc/init.d/smb restart
Example 12: Restart smb every hour between 11 pm and 7 am
0 23-7/1 * * * /etc/init.d/smb restart