Crontab.php 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. <?php
  2. namespace app\admin\controller\general;
  3. use app\common\controller\Backend;
  4. use Cron\CronExpression;
  5. /**
  6. * 定时任务
  7. *
  8. * @icon fa fa-tasks
  9. * @remark 类似于Linux的Crontab定时任务,可以按照设定的时间进行任务的执行,目前仅支持三种任务:请求URL、执行SQL、执行Shell
  10. */
  11. class Crontab extends Backend
  12. {
  13. protected $model = null;
  14. protected $noNeedRight = ['check_schedule', 'get_schedule_future'];
  15. public function _initialize()
  16. {
  17. parent::_initialize();
  18. $this->model = model('Crontab');
  19. $this->view->assign('typedata', \app\common\model\Crontab::getTypeList());
  20. }
  21. /**
  22. * 查看
  23. */
  24. public function index()
  25. {
  26. if ($this->request->isAjax())
  27. {
  28. list($where, $sort, $order, $offset, $limit) = $this->buildparams();
  29. $total = $this->model
  30. ->where($where)
  31. ->order($sort, $order)
  32. ->count();
  33. $list = $this->model
  34. ->where($where)
  35. ->order($sort, $order)
  36. ->limit($offset, $limit)
  37. ->select();
  38. foreach ($list as $k => &$v)
  39. {
  40. $cron = CronExpression::factory($v['schedule']);
  41. $v['nexttime'] = $cron->getNextRunDate()->getTimestamp();
  42. }
  43. $result = array("total" => $total, "rows" => $list);
  44. return json($result);
  45. }
  46. return $this->view->fetch();
  47. }
  48. /**
  49. * 判断Crontab格式是否正确
  50. * @internal
  51. */
  52. public function check_schedule()
  53. {
  54. $row = $this->request->post("row/a");
  55. $schedule = isset($row['schedule']) ? $row['schedule'] : '';
  56. if (CronExpression::isValidExpression($schedule))
  57. {
  58. return json(['ok' => '']);
  59. }
  60. else
  61. {
  62. return json(['error' => __('Crontab format invalid')]);
  63. }
  64. }
  65. /**
  66. * 根据Crontab表达式读取未来七次的时间
  67. * @internal
  68. */
  69. public function get_schedule_future()
  70. {
  71. $time = [];
  72. $schedule = $this->request->post('schedule');
  73. $days = (int) $this->request->post('days');
  74. try
  75. {
  76. $cron = CronExpression::factory($schedule);
  77. for ($i = 0; $i < $days; $i++)
  78. {
  79. $time[] = $cron->getNextRunDate(null, $i)->format('Y-m-d H:i:s');
  80. }
  81. }
  82. catch (\Exception $e)
  83. {
  84. }
  85. return json(['futuretime' => $time]);
  86. }
  87. }