教你在tp6中实现毫秒级定时任务功能
导入 workerman
-
composer require workerman/workerman
复制代码
创建 Timer 命令
-
php think make:command Timer
复制代码
实现 Timer
-
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()
-
{
-
$last = time();
-
$task = [6 => $last, 10 => $last, 30 => $last, 60 => $last, 180 => $last, 300 => $last];
-
-
$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;
-
}
-
}
-
} catch (\Throwable $e) {
-
}
-
});
-
}
-
-
-
}
复制代码
Timer 参数说明
-
Usage:
-
timer [options] [--] <status>
-
-
Arguments:
-
status start/stop/reload/status/connections
-
-
Options:
-
--d daemon(守护进程)方式启动
-
--i[=I] 多长时间执行一次,可以精确到0.001
复制代码
注册 Timer 命令
修改 console.php 文件
-
'commands' => [
-
//定时任务命令
-
'timer'=>\app\command\Timer::class,
-
],
复制代码
启动定时器
-
php think timer start
复制代码
关闭定时器
-
php think timer stop
免责声明:以上内容源自网络,版权归原作者所有,如有侵犯您的原创版权请告知,我们将尽快删除相关内容。
相关新闻
![]()
2018.10.29
0
中文编码问题是用中文的程序员经常头大的问题,在python下也是如此,那么应该怎么理解和解决python的编码问题呢?
![]()
2018.10.29
0
中文编码问题是用中文的程序员经常头大的问题,在python下也是如此,那么应该怎么理解和解决python的编码问题呢?
![]()
2018.10.29
0
中文编码问题是用中文的程序员经常头大的问题,在python下也是如此,那么应该怎么理解和解决python的编码问题呢?