1.安装workerman
composer require workerman/workerman
composer require workerman/crontab
2.创建定时任务文件
php think make:command Timer
3.文件内容
<?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;
use \Workerman\Worker;
use \Workerman\Lib\Timer;
class Timer extends Command
{
/**
* @var int
*/
protected $timer;
/**
* @var int|float
*/
//如需更改时间 请更改 interval 以秒为单位
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('开启/关闭/重启 game00001定时任务');
}
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()
{
$last = time();
$task = [6 => $last, 10 => $last, 30 => $last, 60 => $last, 180 => $last, 300 => $last];
$url='/api/game/text?game_id=1&user_id=1';
$this->timer = \Workerman\Lib\Timer::add($this->interval, function () use (&$task) {
//每隔2秒执行一次
try {
$now = time();
foreach ($task as $sec => $time) {
if ($now - $time >= $sec) {
//每隔$sec秒执行一次
$task[$sec] = $now;
$this->curl_get($url);
}
}
} catch (\Throwable $e) {
}
});
}
public function curl_get($url)
{
$info = curl_init();
curl_setopt($info,CURLOPT_RETURNTRANSFER,true);
curl_setopt($info,CURLOPT_HEADER,0);
curl_setopt($info,CURLOPT_NOBODY,0);
curl_setopt($info,CURLOPT_SSL_VERIFYPEER,false);
curl_setopt($info,CURLOPT_SSL_VERIFYPEER,false);
curl_setopt($info,CURLOPT_SSL_VERIFYHOST,false);
curl_setopt($info,CURLOPT_URL,$url);
$output = curl_exec($info);
curl_close($info);
return $output;
}
}