一、目标
掌握linux的计划任务,或者叫定时任务crontab的用法
二、平台
centos7.6
三、crontab的格式
基本格式 :
* * * * * command
分 时 日 月 周 命令
第1列表示分钟1~59 每分钟用*或者 */1表示
第2列表示小时1~23(0表示0点)
第3列表示日期1~31
第4列表示月份1~12
第5列标识号星期0~6(0表示星期天)
第6列要运行的命令
四、例子
1.每周一到周五的每天下午三点半:30 15 * * 1-5 xCommand
2.每周二四六的早上9点10分:10 9 * * 2,4,6 xCommand
3.每天1点到23点之间每隔两小时:0 1-23/2 * * * xCommand
4.每隔两天:0 0 */3 * * xCommand
5.每天早上8.59开启ssh服务:59 08 * * * systemctl start sshd
6.每天晚上21.37关闭ssh服务:37 21 * * * systemctl stop sshd
五、实例
1.每天早上8.59开启ssh服务:59 08 * * * systemctl start sshd
2.每天晚上21.37关闭ssh服务:37 21 * * * systemctl stop sshd
3.执行命令编辑计划任务(以root用户创建,也可以用其他用户,但必须有执行该任务权限的用户才行)
crontab -e -u root
4.写入计划,#是注释符,wq保存退出
59 08 * * * systemctl start sshd
37 21 * * * systemctl stop sshd
5.查看计划任务
crontab -l -u root
六、实例二
每天22:59备份httpd目录
1.执行命令crontab -e -u root
2.写入计划任务的命令
#3.每天22:59备份httpd目录
59 22 * * * tar -czvf httpd.bak.gz /etc/httpd
3.查看计划任务
root@localhost ~]# crontab -l -u root
#1.每天早上8.59开启ssh服务:59 08 * * * systemctl start sshd
#2.每天晚上21.37关闭ssh服务:37 21 * * * systemctl stop sshd
59 08 * * * systemctl start sshd
37 21 * * * systemctl stop sshd
#3.每天22:59备份httpd目录
59 22 * * * tar -czvf httpd.bak.gz /etc/httpd
七、实例三
每周六早上5.30重启httpd服务
1.执行crontab -e -u root
2.写入任务计划的命令 30 5 * * 6 systemctl restart httpd
3.保存退出wq
八、删除所有计划任务,执行命令crontab -r (直接删除所有计划任务,无法恢复)
kahn 2019年6月23日09:53:55