纵有疾风起
人生不言弃

Linux 定时任务 Crontab按秒执行

 

目前在crontab中最小执行时间单位为分钟。

如果需要按秒来执行,有以下两种方法:

 

方法一:通过sleep来实现

例:

1、创建test.php文件,这里测试通过打印时间好区分。

<?php    file_put_contents('log.txt',date('Y-m-d H:i:s') . "\n", FILE_APPEND);?>

2、确保单独访问test.php文件能打印日志。

3、编辑crontab文件,通过crontab -e 命令,比如我要每15秒运行一次,内容如下:

* * * * * curl "http://127.0.0.1/testtask/test.php" && sleep 15;curl "http://127.0.0.1/testtask/test.php" && sleep 15;curl "http://127.0.0.1/testtask/test.php" && sleep 15;curl "http://127.0.0.1/testtask/test.php"

4、打印结果,可以通过 tail -f log.txt 命令实时查看结果。

Linux 定时任务 Crontab按秒执行插图

可以看到每15秒打印出来结果。

 

 

方法二:通过添加中间shell脚本来实现

例:

1、添加脚本文件 test.sh,内容如下:我这里是选择2秒执行一次。

step=2 #间隔秒数for ((i = 0; i < 60; i = (i + step))); do    $(curl "http://127.0.0.1/testtask/test.php")    sleep $stepdoneexit 0

2、编辑crontab文件

* * * * * /phpstudy/www/testtask/test.sh

3、打印结果

Linux 定时任务 Crontab按秒执行插图1

 

文章转载于:https://www.cnblogs.com/woods1815/p/10959223.html

原著是一个有趣的人,若有侵权,请通知删除

未经允许不得转载:起风网 » Linux 定时任务 Crontab按秒执行
分享到: 生成海报

评论 抢沙发

评论前必须登录!

立即登录