Crontab.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  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 按照设定的时间进行任务的执行,目前支持三种任务:请求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('typeList', \app\admin\model\Crontab::getTypeList());
  20. $this->assignconfig('typeList', \app\admin\model\Crontab::getTypeList());
  21. }
  22. /**
  23. * 查看
  24. */
  25. public function index()
  26. {
  27. if ($this->request->isAjax()) {
  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. $time = time();
  39. foreach ($list as $k => &$v) {
  40. $cron = CronExpression::factory($v['schedule']);
  41. $v['nexttime'] = $time > $v['endtime'] ? __('None') : $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. $this->success();
  58. } else {
  59. $this->error(__('Crontab format invalid'));
  60. }
  61. }
  62. /**
  63. * 根据Crontab表达式读取未来七次的时间
  64. * @internal
  65. */
  66. public function get_schedule_future()
  67. {
  68. $time = [];
  69. $schedule = $this->request->post('schedule');
  70. $days = (int)$this->request->post('days');
  71. try {
  72. $cron = CronExpression::factory($schedule);
  73. for ($i = 0; $i < $days; $i++) {
  74. $time[] = $cron->getNextRunDate(null, $i)->format('Y-m-d H:i:s');
  75. }
  76. } catch (\Exception $e) {
  77. }
  78. $this->success("", null, ['futuretime' => $time]);
  79. }
  80. }