TP5 用cron實現linux定時任務
1) tp5的控制器內容:
namespace app\test\controller;
use think\Controller; use think\facade\Log; class Test extends Controller{ public function testCrontab(){
// 定時執行的代碼。。。 開始 Log::error('start test crond demo.....');
Log::error('end test crond demo.....');
// 定時執行的代碼。。。 結束
}
}
2) 新建文件:crontab.sh,寫入以下內容,並放在項目的根目錄,(如果是TP5,與public目錄平級)
#!/bin/bash
/server/php-5.6.38/bin/php /project/test_project/public/index.php test/test/testCrontab
說明:public為tp5的執行目錄,test/test/testCrontab為:模塊/控制器/操作
3). linux后台,輸入 crontab -e,寫入以下內容(第一個sh后面的路徑為第2步的crontab.sh的全路徑),寫入的內容將生成一個文件,自動保存為/var/spool/cron/root文件,root為當前linux登錄的用戶名。
*/1 * * * * sh /[項目根目錄]/crontab.sh
說明: 前面5個星意義:
基本格式 :
* * * * * command
分 時 日 月 周 命令
第1列表示分鍾1~59 每分鍾用*或者 */1表示
第2列表示小時1~23(0表示0點)
第3列表示日期1~31
第4列表示月份1~12
第5列標識號星期0~6(0表示星期天)
第6列要運行的命令
4)重啟crond服務
service crond restart
說明:crontab -l 可以查看當前的定時任務。
5) 經過以上配置,上述TP5的控制器內的操作1分鍾將會執行一次。
public function testCrontab(){
// 定時執行的代碼。。。 開始
Log::error('start test crond demo.....'); Log::error('end test crond demo.....'); // 定時執行的代碼。。。 結束 }