linux 指定时间执行命令、周期性执行任务
指定时间执行命令(单次执行)
使用at命令:
先安装 yum install at
atq
或者 at -l
查看任务列表
-f
脚本文件,指定所要提交的脚本文件
-t
执行脚本的时间,时间格式为 [[CC]YY]MMDDhhmm
at -r job-id
删除任务
at -f test.sh now
立即执行任务(运行sh)
at -f test.sh now+2 min
两分钟后执行
at -f test.sh -t 11151550
11月15日15:50执行任务
at -f test.sh -t 202211151547
2022年11月15日15:47执行任务
周期性任务(定时器)
例如每天都要干xxx,隔一段时间就需要执行一遍命令。
使用crontab。
先安装:
- Centos:yum -y install vixie-cron crontabs
- ubuntu:apt-get install cron
查看cond 状态:service crond status
启动cron:service crond start
关闭cron:service crond stop
重启cron:service crond restart
crontab -e 进入编辑文件,Ctrl+x退出。
* * * * * command
分 时 日 月 周 命令
第1列表示分钟1~59 每分钟用或者 /2表示
第2列表示小时1~23(0表示0点)
第3列表示日期1~31
第4列表示月份1~12
第5列标识号星期0~6(0表示星期天)
第6列要运行的命令
30 21 * * * /usr/local/etc/rc.d/lighttpd restart
上面的例子表示每晚的21:30重启apache。
45 4 1,10,22 * * /usr/local/etc/rc.d/lighttpd restart
上面的例子表示每月1、10、22日的4 : 45重启apache。
10 1 * * 6,0 /usr/local/etc/rc.d/lighttpd restart
上面的例子表示每周六、周日的1 : 10重启apache。
0,30 18-23 * * * /usr/local/etc/rc.d/lighttpd restart
上面的例子表示在每天18 : 00至23 : 00之间每隔30分钟重启apache。
0 23 * * 6 /usr/local/etc/rc.d/lighttpd restart
上面的例子表示每星期六的11 : 00 pm重启apache。
* */2 * * * /usr/local/etc/rc.d/lighttpd restart
每两小时重启apache
* 23-7/1 * * * /usr/local/etc/rc.d/lighttpd restart
晚上11点到早上7点之间,每隔一小时重启apache
0 11 4 * mon-wed /usr/local/etc/rc.d/lighttpd restart
每月的4号与每周一到周三的11点重启apache
0 4 1 jan * /usr/local/etc/rc.d/lighttpd restart
一月一号的4点重启apache
需求:每分钟要干一些事情
*/1 * * * *
重启crontab,使配置生效:systemctl restart crond.service 或者 service crond restart
crontab -l 查看当前任务
crontab -r 删除任务