下载composer?
composer require workerman/workerman
?创建?Timer 命令
php think make:command Timer
?实现?Timer
<?php
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;
use Workerman\Worker;
//引用控制器
use app\api\controller\Express;
class Timer extends Command
{
/**
* @var int
*/
protected $timer;
/**
* @var int|float
*/
protected $interval = 2;
protected function configure()
{
// 指令配置
$this->setName('timer')
->addArgument('status', Argument::REQUIRED, 'start/stop/reload/status/connections')
->addOption('d', null, Option::VALUE_NONE, 'daemon(守护进程)方式启动')
->addOption('i', null, Option::VALUE_OPTIONAL, '多长时间执行一次')
->setDescription('开启/关闭/重启 定时任务');
}
protected function init(Input $input, Output $output)
{
global $argv;
if ($input->hasOption('i'))
$this->interval = floatval($input->getOption('i'));
$argv[1] = $input->getArgument('status') ?: 'start';
if ($input->hasOption('d')) {
$argv[2] = '-d';
} else {
unset($argv[2]);
}
}
protected function execute(Input $input, Output $output)
{
$this->init($input, $output);
//创建定时器任务
$task = new Worker();
$task->count = 1;
$task->onWorkerStart = [$this, 'start'];
$task->runAll();
}
public function stop()
{
//手动暂停定时器
\Workerman\Lib\Timer::del($this->timer);
}
public function start()
{
//workerman的Timer定时器类 add ,$time_interval是多长时间执行一次
$time = 1800;
\Workerman\Lib\Timer::add($time,function (){
//运行控制器方法
return Express::Work();
});
}
}
修改 console.php?
'commands' => [
//定时任务命令
'timer'=>\app\command\Timer::class,
],
?启动定时任务
php think timer start
关闭定时任务
php think timer stop
|