Set timed tasks
You can use the crontab tool in Linux to set up scheduled tasks. The specific steps are as follows:
- Open the terminal, enter
crontab -e
the command, and open the crontab editor. - In the editor, enter
30 9 * * 1-5 command
, where30 9 * * 1-5
indicates 9:30 every Monday to Friday, andcommand
indicates the command to be executed. - After editing, save and exit the editor.
For example, if you want to execute it at 9:30 every Monday to Friday /usr/bin/python3 /home/user/main.py
, you can enter the following command in the crontab editor:
# 定时 python3 main.py文件的路径
30 9 * * 1-5 /usr/bin/python3 /home/user/main.py
After saving and exiting the editor, the system will execute the command every Monday to Friday at 9:30 /usr/bin/python3 /home/user/main.py
.
The role of * * * * * in crontab
* * * * *
It is the time format in Linux scheduled tasks. It is composed of 5 fields, which respectively represent minutes, hours, dates, months, and days of the week. Their meanings are as follows:
- The first field indicates minutes, and the value range is 0-59;
- The second field indicates the hour, and the value range is 0-23;
- The third field represents the date, and the value range is 1-31;
- The fourth field indicates the month, and the value range is 1-12;
- The fifth field indicates the day of the week, and the value range is 0-6, where 0 means Sunday, 1 means Monday, and so on.
Each field can use the following value methods:
*
: Indicates any value, that is, does not limit the specific value;*/n
: means every n values, for example*/5
means every 5 values, namely 5, 10, 15, 20...;n1,n2,n3
: Indicates that the value is n1, n2, n3 and other specified values;n1-n2
: Indicates that the value range is from n1 to n2, for example,1-5
indicates that the values are 1, 2, 3, 4, 5.
Therefore, * * * * *
means to execute a task every minute, and 30 9 * * 1-5
means to execute a task at 9:30 every Monday to Friday.