在 application/admin/command 目錄下新建一個 Test.php 文件
namespace app\admin\command; use think\console\Command; use think\console\Input; use think\console\Output; use think\Db; class Test extends Command { protected function configure(){ $this->setName('test')->setDescription("計划任務 Test"); } // 調用Test 這個類時,自動調用 execute 這個方法 protected function execute(Input $input, Output $output){ $output->writeln('Date Crontab job start...'); /*** 這里寫計划任務列表集 START ***/ $this->test(); /*** 這里寫計划任務列表集 END ***/ $output->writeln('Date Crontab job end...'); } private function test() { echo '定時任務成功啦~'; } }
修改 application/command.php
return [ 'app\admin\command\Test' ];
進入項目目錄 (並非是根目錄) ,使用命令查看
php think
運行定時任務
php think test
Liunx 中編輯crontab
# 編輯crontab crontab -e # 進入編輯模式后添加如下內容 * * * * * php /home/wwwroot/demo.com/think test # 每分鍾執行一次計划任務 # 保存退出后重啟crontab /etc/init.d/crond restart
效果圖如下:
如果沒有使用ThinkPHP 自身的定時任務,需要執行指定控制器,在Liunx 中編輯 crontab
* * * * * /usr/bin/php /www/yoursite/public/index.php /tool/Crontab/execCrontab > /dev/null 2>&1 &