Skip to content

定时任务—Crontab

* * * commandM H D m d command

  • M: 分(0-59)

  • H: 时(0-23)

  • D: 天(1-31)

  • m: 月(1-12)

  • d: 周(0-6) 0 为星期日

  • * 代表取值范围内的数字

  • / 代表 "每"

  • - 代表从某个数字到某个数字

  • , 代表离散的取值(取值的列表)

Crontab 脚本示例

  1. 每分钟执行*:* * * * * python test.py 等价于 */1 * * * * python test.py。*注意,每分钟的意思是指,每分钟的第 1 秒开始执行。
  2. 每 4 小时执行: */4 * * python test.py
  3. 每周日执行: * * 0 python test.py
  4. 每周六、周日执行: * * 6,0 python test.py
  5. 每小时的第 5 分钟执行:5 * * python test.py

Crontab 脚本编辑

编辑定时任务:

bash
crontab -e # 进入编辑模式

加入:0 16 * python /opt/test.py

保存,退出即可。

当我们编辑完定时任务过后,记得重载一遍 crond:

bash
systemctl reload crond.service

启动、停止、重启服务:

bash
systemctl start crond.service
systemctl stop crond.service
systemctl restart crond.service

设置开机自启:

bash
systemctl enable crond # 开机自启动