SystemCrontabListener.php 3.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. <?php
  2. namespace app\listener\crontab;
  3. use app\services\system\crontab\CrontabRunServices;
  4. use app\services\system\crontab\SystemCrontabServices;
  5. use crmeb\interfaces\ListenerInterface;
  6. use think\helper\Str;
  7. use Workerman\Crontab\Crontab;
  8. /**
  9. * 系统定时任务
  10. */
  11. class SystemCrontabListener implements ListenerInterface
  12. {
  13. public function handle($event): void
  14. {
  15. $systemCrontabServices = app()->make(SystemCrontabServices::class);
  16. $crontabRunServices = app()->make(CrontabRunServices::class);
  17. //自动写入文件方便检测是否启动定时任务命令
  18. new Crontab('*/6 * * * * *', function () {
  19. file_put_contents(root_path() . 'runtime/.timer', time());
  20. });
  21. $list = $systemCrontabServices->selectList(['is_del' => 0, 'is_open' => 1])->toArray();
  22. foreach ($list as &$item) {
  23. //转化小驼峰
  24. $functionName = Str::camel($item['mark']);
  25. //获取定时任务时间字符串
  26. $timeStr = $this->getTimerStr($item);
  27. new Crontab($timeStr, function () use ($crontabRunServices, $functionName) {
  28. $crontabRunServices->$functionName();
  29. });
  30. }
  31. }
  32. /**
  33. * 获取定时任务时间表达式
  34. * 0 1 2 3 4 5
  35. * | | | | | |
  36. * | | | | | +------ day of week (0 - 6) (Sunday=0)
  37. * | | | | +------ month (1 - 12)
  38. * | | | +-------- day of month (1 - 31)
  39. * | | +---------- hour (0 - 23)
  40. * | +------------ min (0 - 59)
  41. * +-------------- sec (0-59)[可省略,如果没有0位,则最小时间粒度是分钟]
  42. * @param $data
  43. * @return string
  44. */
  45. public function getTimerStr($data): string
  46. {
  47. $timeStr = '';
  48. switch ($data['type']) {
  49. case 1:// 每隔几秒
  50. $timeStr = '*/' . $data['second'] . ' * * * * *';
  51. break;
  52. case 2:// 每隔几分
  53. $timeStr = '0 */' . $data['minute'] . ' * * * *';
  54. break;
  55. case 3:// 每隔几时第几分钟执行
  56. $timeStr = '0 ' . $data['minute'] . ' */' . $data['hour'] . ' * * *';
  57. break;
  58. case 4:// 每隔几日第几小时第几分钟执行
  59. $timeStr = '0 ' . $data['minute'] . ' ' . $data['hour'] . ' */' . $data['day'] . ' * *';
  60. break;
  61. case 5:// 每日几时几分几秒
  62. $timeStr = $data['second'] . ' ' . $data['minute'] . ' ' . $data['hour'] . ' * * *';
  63. break;
  64. case 6:// 每周周几几时几分几秒
  65. $timeStr = $data['second'] . ' ' . $data['minute'] . ' ' . $data['hour'] . ' * * ' . ($data['week'] == 7 ? 0 : $data['week']);
  66. break;
  67. case 7:// 每月几日几时几分几秒
  68. $timeStr = $data['second'] . ' ' . $data['minute'] . ' ' . $data['hour'] . ' ' . $data['day'] . ' * *';
  69. break;
  70. }
  71. return $timeStr;
  72. }
  73. }