前段時間在研究thinkphp5.0版本做自動任務的時候,碰到了棘手的問題–如何做自動化任務,因爲程序開始就需要一直執行,查了很多資料,都說靠php原生的死循環來做不靠譜,時間誤差也沒法保證,所以後面採用thinkphp5的command工具和服務器的定時任務來做:
1.新建command文件
在application/模塊/新建一個command文件夾/Test.class.php
<?php
namespace app\admin\command;
use think\console\Command;
use think\console\Input;
use think\console\Output;
class Test extends Command
{
protected function configure(){
$this->setName('Test')->setDescription("計劃任務 Test");
}
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 "test\r\n";
}
}
2.配置command.php文件,位置在application/command.php
<?php
return ['app\admin\command\Test'];
3.運行test命令
打開命令行,運行php think Test命令test命令execute方法中運行的方法就會運行
4.在應用根目錄新建bat文件
task.bat文件
D:
cd D:\xampp\htdocs\autobet
php think Test
5.將bat文件添加到服務器計劃任務
這個根據window和Linux系統不一樣,定時任務設置方法也不同,可以自行百度,我用的是本地的windows服務,詳情看百度經驗:Windows計劃任務設置,定時執行指定腳本
ps:這裏設置間隔時常,可以是1分鐘到31天,可選項最低是5分鐘,可以手寫!