Crontab.php 3.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | likeshop100%开源免费商用商城系统
  4. // +----------------------------------------------------------------------
  5. // | 欢迎阅读学习系统程序代码,建议反馈是我们前进的动力
  6. // | 开源版本可自由商用,可去除界面版权logo
  7. // | 商业版本务必购买商业授权,以免引起法律纠纷
  8. // | 禁止对系统程序代码以任何目的,任何形式的再发布
  9. // | gitee下载:https://gitee.com/likeshop_gitee
  10. // | github下载:https://github.com/likeshop-github
  11. // | 访问官网:https://www.likeshop.cn
  12. // | 访问社区:https://home.likeshop.cn
  13. // | 访问手册:http://doc.likeshop.cn
  14. // | 微信公众号:likeshop技术社区
  15. // | likeshop团队 版权所有 拥有最终解释权
  16. // +----------------------------------------------------------------------
  17. // | author: likeshopTeam
  18. // +----------------------------------------------------------------------
  19. namespace app\common\command;
  20. use app\common\enum\CrontabEnum;
  21. use think\console\Command;
  22. use think\console\Input;
  23. use think\console\Output;
  24. use Cron\CronExpression;
  25. use think\facade\Console;
  26. /**
  27. * 定时任务
  28. * Class Crontab
  29. * @package app\command
  30. */
  31. class Crontab extends Command
  32. {
  33. protected function configure()
  34. {
  35. $this->setName('crontab')
  36. ->setDescription('定时任务');
  37. }
  38. protected function execute(Input $input, Output $output)
  39. {
  40. $lists = \app\common\model\Crontab::where('status', CrontabEnum::START)->select()->toArray();
  41. if(empty($lists)) {
  42. return false;
  43. }
  44. foreach($lists as $item) {
  45. $nextTime = (new CronExpression($item['expression']))
  46. ->getNextRunDate($item['last_time'])
  47. ->getTimestamp();
  48. if($nextTime > time()) {
  49. // 未到时间,不执行
  50. continue;
  51. }
  52. // 开始执行
  53. self::start($item);
  54. }
  55. }
  56. public static function start($item)
  57. {
  58. // 开始执行
  59. $startTime = microtime(true);
  60. try {
  61. $params = explode(' ', $item['params']);
  62. if (is_array($params) && !empty($item['params'])) {
  63. Console::call($item['command'], $params);
  64. } else {
  65. Console::call($item['command']);
  66. }
  67. // 清除错误信息
  68. \app\common\model\Crontab::where('id', $item['id'])->update(['error' => '']);
  69. } catch(\Exception $e) {
  70. // 记录错误信息
  71. \app\common\model\Crontab::where('id', $item['id'])->update(['error' => $e->getMessage(), 'status' => CrontabEnum::ERROR]);
  72. } finally {
  73. $endTime = microtime(true);
  74. // 本次执行时间
  75. $useTime = round(($endTime - $startTime), 2);
  76. // 最大执行时间
  77. $maxTime = max($useTime, $item['max_time']);
  78. // 更新最后执行时间
  79. \app\common\model\Crontab::where('id', $item['id'])
  80. ->update(['last_time' => time(), 'time' => $useTime, 'max_time' => $maxTime]);
  81. }
  82. }
  83. }