Linux crontab 实现秒级定时任务

1   crontab 的延时: 原理:经过延时方法 sleep N  来实现每N秒执行。php

crontab -e 输入如下语句,而后 :wq 保存退出。shell

* * * * * /usr/bin/curl http://www.test.com
* * * * * sleep 5; /usr/bin/curl http://www.test.com
* * * * * sleep 10; /usr/bin/curl http://www.test.com
* * * * * sleep 15; /usr/bin/curl http://www.test.com
* * * * * sleep 20; /usr/bin/curl http://www.test.com
* * * * * sleep 25; /usr/bin/curl http://www.test.com
* * * * * sleep 30; /usr/bin/curl http://www.test.com
* * * * * sleep 35; /usr/bin/curl http://www.test.com
* * * * * sleep 40; /usr/bin/curl http://www.test.com
* * * * * sleep 45; /usr/bin/curl http://www.test.com
* * * * * sleep 50; /usr/bin/curl http://www.test.com
* * * * * sleep 55; /usr/bin/curl http://www.test.com

 

注意:ubuntu

60必须能整除间隔的秒数(没有余数),例如间隔的秒数是2,4,6,10,12等。bash

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

 

2 shell 脚本实现curl

crontab.sh学习

#!/bin/bash  
  
step=2 #间隔的秒数,不能大于60  
  
for (( i = 0; i < 60; i=(i+step) )); do  
    $(php '/home/fdipzone/php/crontab/tolog.php')  
    sleep $step  
done  
  
exit 0

crontab -e 输入如下语句,而后:wq 保存退出。url

# m h  dom mon dow   command  
* * * * * /home/fdipzone/php/crontab/crontab.sh  

使用如下命令查看结果spa

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

原理:在sh使用for语句实现循环指定秒数执行。code

 

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

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

# m h  dom mon dow   command  
*/7 * * * * /home/fdipzone/php/crontab/crontab.sh  

参考网上,仅供学习交流  

 欢迎交流反馈

相关文章
相关标签/搜索