cron服务是Linux内置服务,默认不会开机自动启动。可用以下命令启动和停止服务,也可以设置成开机启动:
systemctl start crond
启动cron服务
systemctl stop crond
停止cron服务
systemctl restart crond
重启cron服务
systemctl enable crond.service
设置cron开机启动
查看当前crontab,输入 crontab -l
编辑当前crontab,输入 crontab -e
删除当前crontab,输入 crontab -r
添加定时任务
crontab -e
0 */1 * * * command 0 */2 * * * command
查询任务是否添加:
crontab -l -u root
#查看root用户
任务添加格式 :
* * * * * command
分 时 日 月 周 命令
* * * * * command
分 时 日 月 周 命令
第1列表示分钟1~59 每分钟用*或者 */1表示
第2列表示小时0~23(0表示0点)
第3列表示日期1~31
第4列表示月份1~12
第5列标识号星期0~6(0表示星期天)
第6列要执行的命令
第2列表示小时0~23(0表示0点)
第3列表示日期1~31
第4列表示月份1~12
第5列标识号星期0~6(0表示星期天)
第6列要执行的命令
crontab文件的例子:
30 21 * * * systemctl restart httpd.service
表示每晚21:30重启apache。
表示每晚21:30重启apache。
45 4 1,10,22 * * systemctl restart httpd.service
表示每月1、10、22日的4 : 45重启apache。
表示每月1、10、22日的4 : 45重启apache。
10 1 * * 6,0 systemctl restart httpd.service
表示每周六、周日的1 : 10重启apache。
表示每周六、周日的1 : 10重启apache。
0,30 18-23 * * * systemctl restart httpd.service
表示在每天18 : 00至23 : 00每隔30分钟重启apache。
表示在每天18 : 00至23 : 00每隔30分钟重启apache。
0 23 * * 6 systemctl restart httpd.service
表示星期六晚上11点重启apache。
表示星期六晚上11点重启apache。
* */1 * * * systemctl restart httpd.service
每一小时重启apache
每一小时重启apache
* 23-7/1 * * * systemctl restart httpd.service
晚上11点到早上7点之间,每隔一小时重启apache
晚上11点到早上7点之间,每隔一小时重启apache
0 11 4 * mon-wed systemctl restart httpd.service
每月的4号与每周一到周三的11点重启apache
每月的4号与每周一到周三的11点重启apache
0 4 1 jan * systemctl restart httpd.service
表示一月一号的4点重启apache
表示一月一号的4点重启apache