定时任务


新建一个定时控制器(Cron)

目录结构

  1. /app
  2. |--cli
  3. | |--controller
  4. | | |--Cli.php
  5. | | |--Cron.php

路径: /app/cli/controller/Cron.php

Cron.php代码如下:

  1. <?php
  2. namespace app\cli\controller;
  3. class Cron extends Cli
  4. {
  5. /**
  6. * 每天凌晨2点执行
  7. */
  8. public function day_2()
  9. {
  10. //要执行的代码
  11. }
  12. /**
  13. * 每月一号凌晨5:10执行
  14. */
  15. public function month_1_5_10()
  16. {
  17. //要执行的代码
  18. }
  19. public function mReport()
  20. {
  21. //要执行的代码
  22. }
  23. /**
  24. * 每5分钟调用一次
  25. */
  26. public function run()
  27. {
  28. $minute = date('i');
  29. $day = date('H:i');
  30. $week = date('N:H:i'); // N 1 ~ 7
  31. $month = date('j:H:i'); // j 1 ~ 31
  32. $cron_config = Config::load('runtime')->get('cron');
  33. if (array_key_exists($day, $cron_config['day'])) {
  34. $action = $cron_config['day'][$day];
  35. try {
  36. call_user_func([$this, $action]);
  37. } catch (\Exception $exception) {
  38. self::errorLog($exception, $action);
  39. }
  40. Log::write(['day' => $day, 'action' => $action], 'Normal', 'cron/run');
  41. }
  42. if (array_key_exists($week, $cron_config['week'])) {
  43. $action = $cron_config['week'][$week];
  44. try {
  45. call_user_func([$this, $action]);
  46. } catch (\Exception $exception) {
  47. self::errorLog($exception, $action);
  48. }
  49. Log::write(['week' => $week, 'action' => $action], 'Normal', 'cron/run');
  50. }
  51. if (array_key_exists($month, $cron_config['month'])) {
  52. $action = $cron_config['month'][$month];
  53. try {
  54. call_user_func([$this, $action]);
  55. } catch (\Exception $exception) {
  56. self::errorLog($exception, $action);
  57. }
  58. Log::write(['month' => $month, 'action' => $action], 'Normal', 'cron/run');
  59. }
  60. if (array_key_exists('10m', $cron_config['loop']) && intval($minute) % 10 == 0) {
  61. $action = $cron_config['loop']['10m'];
  62. call_user_func([$this, $action]);
  63. }
  64. }
  65. }

配置定时任务

配置文件位置

  1. /app/cli/config.php

配置文件解释

  1. 配置名称叫cron
  2. 选项有 day week month loop
  3. day 配置每天几点几分执行
  4. week 配置每周周几几点几分执行
  5. month 配置每月几号几点几分执行
  6. 比如:
  7. 'month' => [
  8. '1:05:00' => 'month_1_5_00',
  9. ],
  10. 每月15点整执行Cron控制器的“month_1_5_00”这个方法,当然这个方法名是自定义的,比如,可以叫“mReport”(月报)
  11. 'month' => [
  12. '1:05:00' => 'mReport',
  13. ],

配置文件内容

  1. <?php
  2. return [
  3. 'cron' => [
  4. 'day' => [
  5. '02:00' => 'day_2',
  6. '02:10' => 'day_2_10',
  7. '02:40' => 'day_2_40',
  8. '03:00' => 'day_3',
  9. '04:00' => 'day_4',
  10. ],
  11. 'week' => [
  12. '1:02:30' => 'week_1_2_30',
  13. '1:02:50' => 'week_1_2_50',
  14. ],
  15. 'month' => [
  16. '1:05:00' => 'month_1_5_00',
  17. '1:05:05' => 'month_1_5_05',
  18. '1:05:10' => 'month_1_5_10',
  19. ],
  20. 'loop' => [
  21. '10m' => 'everyTenMinutes'
  22. ],
  23. ],
  24. ];