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

三、打印結果

相關文章
相關標籤/搜索