Timer.php 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. <?php
  2. declare (strict_types = 1);
  3. namespace app\command;
  4. use think\console\Command;
  5. use think\console\Input;
  6. use think\console\input\Argument;
  7. use think\console\input\Option;
  8. use think\console\Output;
  9. use Workerman\Worker;
  10. class Timer extends Command
  11. {
  12. // 定时器
  13. protected $timer;
  14. protected $interval = 2;
  15. protected function configure()
  16. {
  17. $this->setName('timer')
  18. ->addArgument('status', Argument::REQUIRED, 'start/stop/reload/status/connections')
  19. ->addOption('d', null, Option::VALUE_NONE, 'daemon(守护进程)方式启动')
  20. ->addOption('i', null, Option::VALUE_OPTIONAL, '多长时间执行一次')
  21. ->setDescription('开启/关闭/重启 定时任务');
  22. // 指令配置
  23. // $this->setName('timer')
  24. // ->setDescription('the timer command');
  25. }
  26. protected function init(Input $input, Output $output)
  27. {
  28. global $argv;
  29. if ($input->hasOption('i'))
  30. $this->interval = floatval($input->getOption('i'));
  31. $argv[1] = $input->getArgument('status') ?: 'start';
  32. if ($input->hasOption('d')) {
  33. $argv[2] = '-d';
  34. } else {
  35. unset($argv[2]);
  36. }
  37. }
  38. protected function execute(Input $input, Output $output)
  39. {
  40. $this->init($input, $output);
  41. //创建定时器任务
  42. $task = new Worker();
  43. $task->count = 1;
  44. $task->onWorkerStart = [$this, 'start'];
  45. $task->runAll();
  46. }
  47. public function start()
  48. {
  49. $last = time();
  50. $task = [6 => $last, 10 => $last, 30 => $last, 60 => $last, 180 => $last, 300 => $last];
  51. $this->timer = \Workerman\Lib\Timer::add($this->interval, function () use (&$task) {
  52. //每隔2秒执行一次
  53. try {
  54. $now = time();
  55. foreach ($task as $sec => $time) {
  56. if ($now - $time >= $sec) {
  57. //每隔$sec秒执行一次
  58. $task[$sec] = $now;
  59. }
  60. }
  61. } catch (\Throwable $e) {
  62. }
  63. });
  64. }
  65. }