Timer.php 2.3 KB

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