crontab 容許最少自動執行間隔為 1 分鐘, 即在 crontab 的格為是:
* * * * * /root/my-script.sh > /dev/null 2>&1
1
*****/root/my-script.sh>/dev/null2>&1
如果需要將自動執行時間設定為少於 1 分鐘, 或者以秒數為單位, 可以透過 crontab 配合 sleep 指令完成, 或者建立一個 shell script 再配合 sleep 實現。
以下會示範在 crontab 或 shell script, 設定每 30 秒自動執行, 如果需要設定其他秒數, 只要修改 sleep 後的秒數即可。
crontab:
如果用 crontab 設定, 例如自動執行的 shells script 是 /root/my-script.sh, 設定成每 30 自動執行一次, 在 crontab 加上兩行:
* * * * * /root/my-script.sh > /dev/null 2>&1
* * * * * sleep 30; /root/my-script.sh > /dev/null 2>&1
1
2
*****/root/my-script.sh>/dev/null2>&1
* * * * * sleep 30;/root/my-script.sh>/dev/null2>&1
上面第一行是正常每份鐘執行 /root/my-script.sh, 而第二行加入了 “sleep 30;” 一段, 即先執行 “sleep 30”, 先等待 30 秒再執行 /root/my-script.sh, 那便可以達到每 30 秒執行的效果。
Shell Script:
另一個方法是透過 Shell Script 實現, 如果要設定自動執行的間隔很頻密, 例如每 5 秒執行一次, 我較建議這個方法, 因為不用 crontab 看起來很凌亂。
首先建立一支簡單的 shell script, 以下叫 auto_run.sh:
#!/bin/sh
while true
do
/root/my-script.sh
sleep 30
done
1
2
3
4
5
6
7
#!/bin/sh
whiletrue
do
/root/my-script.sh
sleep30
done
以上 shell script 會自動每 30 秒執行 /root/my-script.sh, 現在設定 auto_run.sh 可執行權限:
# chmod +x auto_run.sh
1
# chmod +x auto_run.sh
為了該每次開機自動執行, 將 auto_run.sh 加入 /etc/rc.local:
# vi /etc/rc.local
1
# vi /etc/rc.local
在檔案最後加入 auto_run.sh 的位置:
# /root/auto_run.sh
1
# /root/auto_run.sh
儲存檔案後離開編輯器, 重新開機時便會自動執行 /root/auto_run.sh, 而 /root/auto_run.sh 會每 30 秒自動執行 /root/my-script.sh, 如果不想重新開機, 可以用 nohup 指令手動在背景執行 /root/auto_run.sh:
# nohup /root/auto_run.sh &
1
# nohup /root/auto_run.sh &
你可能感興趣的內容: