Import the workerman

composer require workerman/workerman
Copy the code

Create Timer command

php think make:command Timer
Copy the code

To implement the Timer

class Timer extends Command
 {
     /**
      * @var int
      */
     protected $timer;
 
    /**
      * @var int|float
      */
     protected $interval = 2;
 
    protected function configure() {// Directive configuration$this->setName('timer')
             ->addArgument('status', Argument::REQUIRED, 'start/stop/reload/status/connections')
             ->addOption('d', null, Option::VALUE_NONE, 'Daemon start')
             ->addOption('i', null, Option::VALUE_OPTIONAL, 'How often does it happen?') - >setDescription('Enable/disable/Restart scheduled Task');
     }
 
    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); // Create a timer task$task = new Worker();
         $task->count = 1;
 
        $task->onWorkerStart = [$this.'start'];
         $task->runAll();
     }
 
    public function stop() {// Manual pause Timer \Workerman\Lib\Timer::del($this->timer);
     }
 
    public function start()
     {
         $last = time();
         $task= [6 = >$last10 = >,$last30 = >,$last60 = >,$last, 180 = >$last, 300 = >$last];
         
         $this->timer = \Workerman\Lib\Timer::add($this->interval, function () use (&$task) {// Every 2 seconds try {$now = time();
                 foreach ($task as $sec= >$time) {
                     if ($now - $time> =$sec) {// Every other$secExecute once per second$task[$sec] = $now;
                     }
                 }
             } catch (\Throwable $e) {}}); }}Copy the code

Timer Parameter Description

Usage:
   timer [options] [--] <status>
 
Arguments:
   status                start/stop/reload/status/connections
 
Options:
       --dDaemon start -- I [=I] How often to execute, accurate to 0.001Copy the code

Register the Timer command


Modify the console.php file

'commands'=> [// Scheduled task command'timer'=>\app\command\Timer::class,
     ],
Copy the code

Start timer

php think timer start
Copy the code

Off timer

php think timer stop
Copy the code

——–

High-quality open source projects, wechat mall + small program mall: github.crmeb.net/u/gitee