Thinkphp5实现毫秒级定时任务功能 - 知乎

来源: Thinkphp5实现毫秒级定时任务功能 – 知乎

导入workman扩展包

composer require workerman/workerman

创建 Timer 命令

php think make:command SelfTimer
class SelfTimer extends Command
{
    protected $timer;
    protected $interval = 10;
    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) {
            //可以在这里写你想要实现的功能
            echo"wo hao shuai";

             //每隔2秒执行一次
           // try {
              //    $now = time();
              //    foreach ($task as $sec => $time) {
               //       if ($now - $time >= $sec) {
                        //每隔$sec秒执行一次
                //          $task[$sec] = $now;
               //       }
               //   }
             // } catch (\Throwable $e) {
             // }
        });
    }

注册 Timer 命令

修改 command.php 文件

return [
    'app\api\command\SelfTimer', //修改为你的文件地址
];

启动定时器

php think SelfTimer start

关闭定时器

php think SelfTimer stop
赞(0) 打赏
分享到: 更多 (0)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏