Timer.php 2.2 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. $task = new Worker();
  47. $task->count = 1;
  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('Task_2');
  63. foreach ($task as $sec => $time) {
  64. if ($now - $time >= $sec) {
  65. event('Task_' . $sec);
  66. $task[$sec] = $now;
  67. }
  68. }
  69. } catch (\Throwable $e) {
  70. }
  71. });
  72. }
  73. }