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

导入 workerman

composer require workerman/workerman

创建 Timer 命令

php think make:command Timer

实现 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('开启/关闭/重启 定时任务');
    }
    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
  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值