本教程使用的定時任務(wù)基于EasyTak氛濒,EasyTask官方文檔:https://gitee.com/392223903/EasyTask
(1).安裝tp6
composer?create-project?topthink/think?tp
(2).安裝定時任務(wù)composer包
composer?require?easy-task/easy-task
(3).創(chuàng)建命令行處理類文件
php?think?make:command?Task??task
會生成文件:tp\app\command\Task.php
將Task.php文件內(nèi)容修改如下:
<?php
declare?(strict_types=1);
namespace?app\command;
use?think\console\Command;
use?think\console\Input;
use?think\console\input\Argument;
use?think\console\input\Option;
use?think\console\Output;
class?Task?extends?Command
{
????protected?function?configure()
????{
????????//設(shè)置名稱為task
????????$this->setName('task')
????????????//增加一個命令參數(shù)
????????????->addArgument('action',?Argument::OPTIONAL,?"action",?'')
????????????->addArgument('force',?Argument::OPTIONAL,?"force",?'');
????}
????protected?function?execute(Input?$input,?Output?$output)
????{
????????//獲取輸入?yún)?shù)
????????$action?=?trim($input->getArgument('action'));
????????$force?=?trim($input->getArgument('force'));
????????//?配置任務(wù)晨抡,每隔20秒訪問2次網(wǎng)站
????????$task?=?new?\EasyTask\Task();
????????$task->setRunTimePath('./runtime/');
????????$task->addFunc(function?()?{
????????????$url?=?'https://www.gaojiufeng.cn/?id=327';
????????????file_get_contents($url);
????????},?'request',?20,?2);;
????????//?根據(jù)命令執(zhí)行
????????if?($action?==?'start')
????????{
????????????$task->start();
????????}
? ? ?elseif?($action?==?'status')
????????{
????????????$task->status();
????????}
????????elseif?($action?==?'stop')
????????{
????????????$force?=?($force?==?'force');?//是否強(qiáng)制停止
????????????$task->stop($force);
????????}
????????else
????????{
????????????exit('Command?is?not?exist');
????????}
????}
}
(4).配置tp\config\console.php文件
<?php
//?+----------------------------------------------------------------------
//?|?控制臺配置
//?+----------------------------------------------------------------------
return?[
????//?指令定義
????'commands'?=>?[
????????'task'?=>?'app\command\Task',
????],
];
(5).執(zhí)行命令(windows請使用cmd):
php?think?task?start??啟動命令
php?think?task?status?查詢命令
php?think?task?stop???關(guān)閉命令
php??think??task??stop??force???強(qiáng)制關(guān)閉命令