Timer.php 2.3 KB

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