一、安裝workman
composer require workerman/workerman
二、創建 Timer 命令
php think make:command Timers
三、實現Timer
<?php declare (strict_types = 1); namespace app\command; use app\controller\Index; use think\console\Command; use think\console\Input; use think\console\input\Argument; use think\console\input\Option; use think\console\Output; use Workerman\Worker; class Timer extends Command { protected $timer; 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); //創建定時器任務 new Worker('websocket://0.0.0.0:2346'); $task = new Worker(); $task->count = 1; //每個子進程啟動時都會執行$this->start方法 $task->onWorkerStart = [$this, 'start']; //每個子進程連接時都會執行,瀏覽器127.0.0.1:2346,就能調用方法 $task->onConnect = function ($connection) { echo "nihao\n"; }; $task->runAll(); } public function stop() { //手動暫停定時器 \Workerman\Lib\Timer::del($this->timer); } public function start() { // workerman的Timer定時器類 add ,$time_interval是多長時間執行一次 $time_interval = 2.5; \Workerman\Lib\Timer::add($time_interval, function() {
// 運行控制器Index的index echo Index::index(); }); // 下面是網上找的內容 $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 命令 app/config/console.php
修改 console.php 文件
<?php // +---------------------------------------------------------------------- // | 控制台配置 // +---------------------------------------------------------------------- return [ // 指令定義 'commands' => [ //定時任務命令 'timer'=>\app\command\Timer::class, ], ];
五、啟動定時器
php think timer start
六、關閉定時器
php think timer stop
