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 命令實時查看結果。

可以看到每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 $step
done
exit 0

2、編輯crontab文件

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

3、打印結果

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM