Linux启动定时任务

我这里是centos,一般默认都会有这个命令,ubuntu应该也差不多。

启动服务:service crond start

关闭服务:service crond stop 

重启服务:service crond restart 

重新载入配置:service crond reload 

为了启动任务要先编辑/etc/crontab文件

文件是这个样子:

SHELL=/bin/bash
PATH=/sbin:/bin:/usr/sbin:/usr/bin
MAILTO=root
HOME=/

# For details see man 4 crontabs

# Example of job definition:
# .---------------- minute (0 - 59)
# |  .------------- hour (0 - 23)
# |  |  .---------- day of month (1 - 31)
# |  |  |  .------- month (1 - 12) OR jan,feb,mar,apr ...
# |  |  |  |  .---- day of week (0 - 6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat
# |  |  |  |  |
# *  *  *  *  * user-name command to be executed

下面是一些例子可以参考:

5      *       *           *     *  root   ls         指定每小时的第5分钟执行一次ls命令
30     5       *           *     *  root   ls         指定每天的 5:30 执行ls命令
30     7       8           *     *  root   ls         指定每月8号的7:30分执行ls命令
30     5       8           6     *  root   ls         指定每年的6月8日5:30执行ls命令
30     5       8           6     *  root   ls         指定每年的6月8日5:30执行ls命令
30     6       *           *     0  root   ls         指定每星期日的6:30执行ls命令
30     3     10,20         *     *  root   ls         每月10号及20号的3:30执行ls命令
25     8-11    *           *     *  root   ls         每天8-11点的第25分钟执行ls命令
*/15   *       *           *     *  root   ls         每15分钟执行一次ls命令
30     6     */10          *     *  root   ls         每个月中,每隔10天6:30执行一次ls命令

比如我需要每周日下午2点半执行runjob.py的脚本,可以这样写:

30    14    *    *    0    root    python3 runjob.py

配置文件写完保存之后,输入:

service crond reload 
service crond restart 

第一次使用crontab时输入crontab -l 会出现 no crontab for root

解决方法是输入crontab -e,再按vim方式wq保存退出即可。

参考:https://www.jianshu.com/p/61ec46473884

原文地址:https://www.cnblogs.com/tiandsp/p/12731775.html