搜索
系统检测到您的用户名不符合规范:

手把手教你在tp6中实现毫秒级定时任务功能

浏览:16863 发布日期:2019年07月04日 分类:ThinkPHP6专区 关键字: tp6 timer 定时任务
导入 workermancomposer 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-----
高品质的开源项目, 微信商城+小程序商城:
http://github.crmeb.net/u/xaboy
最佳答案
评论() 相关
后面还有条评论,
评论支持使用[code][/code]标签添加代码
您需要登录后才可以评论 登录 | 立即注册
收藏
xaboy
积分:579 等级:LV2
热点推荐
(追記) (追記ここまで)
最新更新

我们

合作

网站

信息

ThinkPHP 是一个免费开源的,快速、简单的面向对象的 轻量级PHP开发框架 ,创立于2006年初,遵循Apache2开源协议发布,是为了敏捷WEB应用开发和简化企业应用开发而诞生的。ThinkPHP从诞生以来一直秉承简洁实用的设计原则,在保持出色的性能和至简的代码的同时,也注重易用性。并且拥有众多的原创功能和特性,在社区团队的积极参与下,在易用性、扩展性和性能方面不断优化和改进,已经成长为国内最领先和最具影响力的WEB应用开发框架,众多的典型案例确保可以稳定用于商业以及门户级的开发。

AltStyle によって変換されたページ (->オリジナル) /