Linux 定时任务 Crontab按秒执行

 

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

若是须要按秒来执行,有如下两种方法:shell

 

方法一:经过sleep来实现

例:curl

一、建立test.php文件,这里测试经过打印时间好区分。测试

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

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

三、编辑crontab文件,经过crontab -e 命令,好比我要每15秒运行一次,内容以下:spa

* * * * * 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"

四、打印结果,能够经过 tail -f log.txt 命令实时查看结果。日志

能够看到每15秒打印出来结果。code

 

 

方法二:经过添加中间shell脚原本实现

例:blog

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

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

二、编辑crontab文件

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

三、打印结果

相关文章
相关标签/搜索