【Linux】crontab -- linux的定时任务

每5秒钟执行一次

方法一

由于 Linux 的 crontab 的定时命令格式如下:

minute hour day-of-month month-of-year day-of-week commands

意味着标椎定时任务中,最小定时周期是分钟。

但是,由于实际应用中,可能需要每5秒就要求执行某个shell脚本。(必须是能把60整除间隔的秒数(也就是没有余数),例如间隔的秒数是2,4,5,6,10,12等。)

该如何实现呢?

本文中提供如下方式;

间隔调用shell命令

crontab 定时脚本如下(只需要将&& 后面的部分,替换成自己需要的脚本执行命令即可):

*/1 * * * * /bin/date >>/tmp/date.txt

*/1 * * * * sleep 5 && /bin/date >>/tmp/date.txt

*/1 * * * * sleep 10 && /bin/date >>/tmp/date.txt

*/1 * * * * sleep 15 && /bin/date >>/tmp/date.txt

*/1 * * * * sleep 20 && /bin/date >>/tmp/date.txt

*/1 * * * * sleep 25 && /bin/date >>/tmp/date.txt

*/1 * * * * sleep 30 && /bin/date >>/tmp/date.txt

*/1 * * * * sleep 35 && /bin/date >>/tmp/date.txt

*/1 * * * * sleep 40 && /bin/date >>/tmp/date.txt

*/1 * * * * sleep 45 && /bin/date >>/tmp/date.txt

*/1 * * * * sleep 50 && /bin/date >>/tmp/date.txt

*/1 * * * * sleep 55 && /bin/date >>/tmp/date.txt

执行效果如下:

794ea9f79553ea991c978e6e31d9a0dc.png

 Linux命令每五分钟执行一次,Linux crontab 每5秒钟执行一次 shell 脚本 的方法_阿阿阿阿枕的博客-CSDN博客

方法二

如果间隔的秒数太少,例如2秒执行一次,这样就需要在crontab 加入60/2=30条语句。不建议使用此方法,可以使用下面介绍的第二种方法。

2 shell 脚本实现

crontab.sh

#!/bin/bash

step=2 #间隔的秒数,不能大于60

for (( i = 0; i < 60; i=(i+step) )); do

$(php '/home/php/xxorg/crontab/tolog.php')

sleep $step

done

exit 0

crontab -e 输入以下语句,然后:wq 保存退出。

* * * * * /home/php/xxorg/crontab/crontab.sh

使用以下命令查看结果

xxorg@ubuntu:~/php/crontab$ tail -f run.log

其实现crontab秒级任务执行的原理:在sh使用for语句实现循环指定秒数执行。

注意:如果60不能整除间隔的秒数,则需要调整执行的时间。例如需要每7秒执行一次,就需要找到7与60的最小公倍数,7与60的最小公倍数是420(即7分钟)。

则 crontab.sh step的值为7,循环结束条件i<420, crontab -e可以输入以下语句来实现

*/7 * * * * /home/php/xxorg/crontab/crontab.sh

3 实现指定第几秒执行crontab任务

通常设置按照每分钟执行的情况如下

* * * * * /usr/bin/curl http://www.xxorg.com

上面的命令会在每分钟的第一秒开始执行crontab任务,那么需要在每分钟的第12秒执行任务怎么办呢?仍然可以使用sleep来实现:

* * * * * sleep 12; /usr/bin/curl http://www.xxorg.com

其实都是使用了sleep延时的方法实现特定的秒级时间点或者时间间隔,只要理解crontab的sleep方法为到达预设时间后,再等待多少秒再执行命令就可以了,用好crontab的sleep会让定时任务的执行更加的灵活。

原文链接:https://blog.csdn.net/weixin_36328790/article/details/112019318

猜你喜欢

转载自blog.csdn.net/bandaoyu/article/details/122623607