Linux CentOS7 下定時任務(秒級別)的實現

系統環境:我的環境是 

cat /etc/redhat-release //看操作系統版本

CentOS Linux release 7.4.1708 (Core) 


一.使用延時來實現每N秒執行  原理:通過延時方法 sleep N  來實現每N秒執行。

寫個php文件

$time = @date("Y-m-d H:i:s");
echo $time;
 file_put_contents('text.txt',$time."\n",FILE_APPEND);

打開 crontab -e 編輯定時任務 每隔10秒執行一次

* * * * *  cd /www/dingshi/;php index.php
* * * * * sleep 10;  cd /www/dingshi/;php index.php
* * * * * sleep 20;  cd /www/dingshi/;php index.php
* * * * * sleep 30;  cd /www/dingshi/;php index.php
* * * * * sleep 40;  cd /www/dingshi/;php index.php
* * * * * sleep 50;  cd /www/dingshi/;php index.php

注意 php是你配置的環境變量  查看  tail -f  /www/dingshi/text.txt   


遇到的坑

之前寫的是  * * * * *  php  /www/dingshi/index.php  等不知道爲什麼文本里就是沒內容,定時任務執行了但是沒有寫入, 權限,重啓定時任務都試了,就是沒寫入,但是在命令行 執行  php  /www/dingshi/index.php 可以執行無語

後來改爲了 * * * * *  cd /www/dingshi/;php index.php


二.編寫shell腳本實現  原理:在sh使用for語句實現循環指定秒數執行。

寫shell腳本執行php文件 將數據寫到文本

  1. #!/bin/bash  
  2.   
  3. step=10 #間隔的秒數,不能大於60  
  4.   
  5. for (( i = 0; i < 60; i=(i+step) )); do  
  6.     $(php 'php  /www/dingshi/index.php')  
  7.     sleep $step  
  8. done  
  9.   
  10. exit 0  

編輯定時  * * * * *  /www/dingshi/crontab.sh 



-----------------------------------------分割線---------- 查看定時任務是否執行,-----------------------------

啓動定時:service crond start crontab的日誌位置一般位於/var/log/cron,利用下面的語句即可查看日誌。  tail -f /var/log/cron

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章