导航

TP6:使用Workerman执行定时任务

Posted on 2022-05-10 11:32  eastson  阅读(2097)  评论(1编辑  收藏  举报

使用Workerman的Timer类,可以定时执行某些任务。

1. 建立app/test/command/Hello2.php。

<?php
declare (strict_types = 1);

namespace app\test\command;

use think\console\Command;
use think\console\Input;
use think\console\Output;
use Workerman\Worker;
use Workerman\Lib\Timer;

class Hello2 extends Command
{
    protected function configure()
    {
        // 指令配置
        $this->setName('hello2')
            ->setDescription('the hello2 command');
    }

    protected function execute(Input $input, Output $output)
    {
        $worker = new Worker();

        $worker->name = $this->getName();

        $worker->onWorkerStart = function() use ($output)
        {
            // 每隔3秒钟执行一次
            Timer::add(3, array($this, 'sayHello'), array($output));
        };

        Worker::runAll();
    }

    public function sayHello(Output $output)
    {
        $output->writeln('Hello ' . date('Y-m-d H:i:s'));
    }
}

2. 配置config\console.php。

<?php

return [
    'commands' => [
        'app\test\command\Hello2',
    ],
];

3. 测试命令执行结果。