Timer.php 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. <?php
  2. namespace crmeb\command;
  3. use Channel\Server;
  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. * @var int
  14. */
  15. protected $timer;
  16. /**
  17. * @var int|float
  18. */
  19. protected $interval = 2;
  20. protected function configure()
  21. {
  22. // 指令配置
  23. $this->setName('timer')
  24. ->addArgument('status', Argument::REQUIRED, 'start/stop/reload/status/connections')
  25. ->addOption('d', null, Option::VALUE_NONE, 'daemon(守护进程)方式启动')
  26. ->addOption('i', null, Option::VALUE_OPTIONAL, '多长时间执行一次,可以精确到0.001')
  27. ->setDescription('start/stop/restart 定时任务');
  28. }
  29. protected function init(Input $input, Output $output)
  30. {
  31. global $argv;
  32. if ($input->hasOption('i'))
  33. $this->interval = floatval($input->getOption('i'));
  34. $argv[1] = $input->getArgument('status') ?: 'start';
  35. if ($input->hasOption('d')) {
  36. $argv[2] = '-d';
  37. } else {
  38. unset($argv[2]);
  39. }
  40. }
  41. protected function execute(Input $input, Output $output)
  42. {
  43. $this->init($input, $output);
  44. Worker::$pidFile = app()->getRootPath() . 'timer.pid';
  45. $task = new Worker();
  46. $task->count = 1;
  47. event('Timer_6');
  48. $task->onWorkerStart = [$this, 'start'];
  49. $task->runAll();
  50. }
  51. public function stop()
  52. {
  53. \Workerman\Lib\Timer::del($this->timer);
  54. }
  55. public function start()
  56. {
  57. $last = time();
  58. $task = [6 => $last, 10 => $last, 30 => $last, 60 => $last, 180 => $last, 300 => $last];
  59. $this->timer = \Workerman\Lib\Timer::add($this->interval, function () use (&$task) {
  60. try {
  61. $now = time();
  62. event('Timer_2');
  63. foreach ($task as $sec => $time) {
  64. if ($now - $time >= $sec) {
  65. event('Timer_' . $sec);
  66. $task[$sec] = $now;
  67. }
  68. }
  69. } catch (\Throwable $e) {
  70. }
  71. });
  72. }
  73. }