Linux下ThinkPHP5實現定時器任務 - 結合crontab


1.在/application/command創建要配置的PHP類文件,需要繼承Command類,並重寫configure和execute兩個方法,例如:

 1 <?php
 2 namespace app\command;
 3 use think\console\Command;
 4 use think\console\Input;
 5 use think\console\Output;
 6 use think\Db;
 7 class Test extends Command
 8 {
 9     // 配置定時器的信息
10     protected function configure()
11     {
12         $this->setName('test')
13             ->setDescription('Command Test');
14     }
15     protected function execute(Input $input, Output $output)
16     {
17         // 輸出到日志文件
18         $output->writeln("TestCommand:");
19         // 定時器需要執行的內容
20         // .....
21         $output->writeln("end....");
22     }
23 }

2.修改application/command.php內容,加入上述的定時器內容

1 <?php
2 return [
3     'application\command\Test', // 加入需要cmd運行的PHP文件
4 ];

3.添加shell執行文件

在項目根目錄下創建shell腳本,例如crond.sh
#!/bin/sh
PATH=/usr/local/php/bin:/opt/someApp/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin # 將php路徑加入都臨時變量中
cd /home/wwwroot/域名/  # 進入項目的根目錄下,保證可以運行php think的命令
php think test # 執行在Test.php設定的名稱
注意:test 可執行命令是ThinkPHP自帶的,可以通過 連接服務器,到/home/wwwroot/域名/ 目錄下,輸入 php think查詢可以被執行的命令,如下:

4.使用crontab設置定時器

有兩種方式,效果是一樣的:

1.連接到服務器,輸入 crontab -e,寫入:

0 0 * * * /home/wwwroot/域名/crond.sh
注意:1).0 0 * * * 是crontab的定時表達式,表示每天的0點0分執行該文件,具體詳情可以訪問 《crontab定時寫法》進行學習。
         2).可以使用crontab -l 的命令查看已登錄的賬戶有幾個定時器。
         3).可以到 /var/log/cron 文件查看日志文件,便於追蹤錯誤。
2.連接到服務器,輸入 vim /etc/crontab, 初始化內容為:
在該文件寫入
0 0 * * * root /home/wwwroot/域名/crond.sh

最終的查看的結果是:

最后保存該文件

5.重啟crond服務

service crond restart

如果 該命令無法重啟,請使用systemctl restart crond 進行重啟

 

----------------------------------------------------------分隔線-------------------------------------------------------------------------

經過網友 @愛菲不變 的提醒,發現還有一個方法,需要修改本文的前三步,后面均一致。

1).新增Controller類,並編寫相對應的方法,例如:

以下是Test Controller類,還有一個簡單的test方法。

<?php

namespace app\demo\controller;

use think\Controller;
use think\Log;

class Test extends Controller
{
    public function test(){
        Log::error('start test  crond demo.....');
        Log::error('end test  crond demo.....');
    }

}

訪問test方法的路由:demo/test/test

2).添加shell執行文件

在項目根目錄下創建shell腳本,例如crond.sh

#!/bin/sh
PATH=/usr/local/php/bin:/opt/someApp/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
# 1.執行 php 命令不需要到thinkphp項目的目錄下 2.index.php為入口文件 3.第三個參數為需要執行方法的路由
php /home/wwwroot/域名/index.php demo/test/test

后面的步驟從本文第4步開始,就可以完成定時功能。

個人意見:第二種方法符合API引用的思維,覺得比較容易被接受,第一種有點引用插件的感覺,對於剛接觸項目的用戶友好一點,可以知道項目的定時器;因此個人覺得這兩種都可以,看個人習慣。


免責聲明!

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



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