SystemCrontabServices.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  1. <?php
  2. namespace app\services\system\crontab;
  3. use app\dao\system\crontab\SystemCrontabDao;
  4. use app\services\BaseServices;
  5. use crmeb\exceptions\AdminException;
  6. use think\facade\Cache;
  7. use think\helper\Str;
  8. use Workerman\Crontab\Crontab;
  9. class SystemCrontabServices extends BaseServices
  10. {
  11. public function __construct(SystemCrontabDao $dao)
  12. {
  13. $this->dao = $dao;
  14. }
  15. /**
  16. * 定时任务列表
  17. * @param array $where
  18. * @return array
  19. * @throws \think\db\exception\DataNotFoundException
  20. * @throws \think\db\exception\DbException
  21. * @throws \think\db\exception\ModelNotFoundException
  22. */
  23. public function getTimerList(array $where = [])
  24. {
  25. [$page, $limit] = $this->getPageValue();
  26. $list = $this->dao->selectList($where, '*', $page, $limit, 'id desc', [], true);
  27. foreach ($list as &$item) {
  28. $item['next_execution_time'] = date('Y-m-d H:i:s', $item['next_execution_time']);
  29. $item['last_execution_time'] = $item['last_execution_time'] != 0 ? date('Y-m-d H:i:s', $item['last_execution_time']) : '暂未执行';
  30. }
  31. $count = $this->dao->count($where);
  32. return compact('list', 'count');
  33. }
  34. /**
  35. * 定时任务详情
  36. * @param $id
  37. * @return array
  38. * @throws \think\db\exception\DataNotFoundException
  39. * @throws \think\db\exception\DbException
  40. * @throws \think\db\exception\ModelNotFoundException
  41. */
  42. public function getTimerInfo($id)
  43. {
  44. $info = $this->dao->get($id);
  45. $info['customCode'] = "<?php\n\n" . json_decode($info['customCode']);
  46. if (!$info) throw new AdminException(100026);
  47. return $info->toArray();
  48. }
  49. /**
  50. * 定时任务类型
  51. * @return string[]
  52. */
  53. public function getMarkList(): array
  54. {
  55. return app()->make(CrontabRunServices::class)->markList;
  56. }
  57. /**
  58. * 保存定时任务
  59. * @param array $data
  60. * @return bool
  61. * @throws \ReflectionException
  62. * @throws \think\db\exception\DataNotFoundException
  63. * @throws \think\db\exception\DbException
  64. * @throws \think\db\exception\ModelNotFoundException
  65. */
  66. public function saveTimer(array $data = [])
  67. {
  68. if (!$data['id'] && $this->dao->getCount(['mark' => $data['mark'], 'is_del' => 0]) && $data['mark'] != 'customTimer') {
  69. throw new AdminException('该定时任务已存在,请勿重复添加');
  70. }
  71. if ($data['mark'] != 'customTimer') $data['name'] = $this->getMarkList()[$data['mark']];
  72. $data['customCode'] = json_encode(preg_replace('/<\?php\s*\n/', '', $data['customCode']));
  73. $data['timeStr'] = $this->getTimerStr([
  74. 'type' => $data['type'],
  75. 'month' => $data['month'],
  76. 'week' => $data['week'],
  77. 'day' => $data['day'],
  78. 'hour' => $data['hour'],
  79. 'minute' => $data['minute'],
  80. 'second' => $data['second'],
  81. ]);
  82. if (!$data['id']) {
  83. unset($data['id']);
  84. $data['add_time'] = $data['update_time'] = time();
  85. $res = $this->dao->save($data);
  86. } else {
  87. $data['update_time'] = time();
  88. $res = $this->dao->update(['id' => $data['id']], $data);
  89. }
  90. if (!$res) throw new AdminException(100006);
  91. Cache::delete('crontabCache');
  92. Cache::set('crontabCache', $this->dao->selectList([])->toArray());
  93. return true;
  94. }
  95. /**
  96. * 删除定时任务
  97. * @param $id
  98. * @return bool
  99. * @throws \ReflectionException
  100. * @throws \think\db\exception\DataNotFoundException
  101. * @throws \think\db\exception\DbException
  102. * @throws \think\db\exception\ModelNotFoundException
  103. */
  104. public function delTimer($id)
  105. {
  106. $data['update_time'] = time();
  107. $data['is_del'] = 1;
  108. $res = $this->dao->update(['id' => $id], $data);
  109. if (!$res) throw new AdminException(100008);
  110. Cache::delete('crontabCache');
  111. Cache::set('crontabCache', $this->dao->selectList([])->toArray());
  112. return true;
  113. }
  114. /**
  115. * 设置定时任务状态
  116. * @param $id
  117. * @param $is_open
  118. * @return bool
  119. * @throws \ReflectionException
  120. * @throws \think\db\exception\DataNotFoundException
  121. * @throws \think\db\exception\DbException
  122. * @throws \think\db\exception\ModelNotFoundException
  123. */
  124. public function setTimerStatus($id, $is_open)
  125. {
  126. $data['update_time'] = time();
  127. $data['is_open'] = $is_open;
  128. $res = $this->dao->update(['id' => $id], $data);
  129. if (!$res) throw new AdminException(100014);
  130. Cache::delete('crontabCache');
  131. Cache::set('crontabCache', $this->dao->selectList([])->toArray());
  132. return true;
  133. }
  134. /**
  135. * 计算定时任务下次执行时间
  136. * @param $data
  137. * @param int $time
  138. * @return false|float|int|mixed
  139. */
  140. public function getTimerCycleTime($data, $time = 0)
  141. {
  142. if (!$time) $time = time();
  143. switch ($data['type']) {
  144. case 1: // 每隔几秒
  145. $cycle_time = $time + $data['second'];
  146. break;
  147. case 2: // 每隔几分
  148. $cycle_time = $time + ($data['minute'] * 60);
  149. break;
  150. case 3: // 每隔几时
  151. $cycle_time = $time + ($data['hour'] * 3600) + ($data['minute'] * 60);
  152. break;
  153. case 4: // 每隔几日
  154. $cycle_time = $time + ($data['day'] * 86400) + ($data['hour'] * 3600) + ($data['minute'] * 60);
  155. break;
  156. case 5: // 每日几时几分几秒
  157. $cycle_time = strtotime(date('Y-m-d ' . $data['hour'] . ':' . $data['minute'] . ':' . $data['second'], time()));
  158. if ($time >= $cycle_time) {
  159. $cycle_time = $cycle_time + 86400;
  160. }
  161. break;
  162. case 6: // 每周周几几时几分几秒
  163. $todayStart = strtotime(date('Y-m-d 00:00:00', time()));
  164. $w = date("w");
  165. if ($w > $data['week']) {
  166. $cycle_time = $todayStart + ((7 - $w + $data['week']) * 86400) + ($data['hour'] * 3600) + ($data['minute'] * 60) + $data['second'];
  167. } else if ($w == $data['week']) {
  168. $cycle_time = $todayStart + ($data['hour'] * 3600) + ($data['minute'] * 60) + $data['second'];
  169. if ($time >= $cycle_time) {
  170. $cycle_time = $cycle_time + (7 * 86400);
  171. }
  172. } else {
  173. $cycle_time = $todayStart + (($data['week'] - $w) * 86400) + ($data['hour'] * 3600) + ($data['minute'] * 60) + $data['second'];
  174. }
  175. break;
  176. case 7: // 每月几日几时几分几秒
  177. $currentMonth = date("n");
  178. $currentYear = date("Y");
  179. if ($currentMonth == 12) {
  180. $nextMonth = 1;
  181. $nextYear = $currentYear + 1;
  182. } else {
  183. $nextMonth = $currentMonth + 1;
  184. $nextYear = $currentYear;
  185. }
  186. $cycle_time = mktime($data['hour'], $data['minute'], $data['second'], $nextMonth, $data['day'], $nextYear);
  187. break;
  188. case 8: // 每年几月几日几时几分几秒
  189. $cycle_time = mktime($data['hour'], $data['minute'], $data['second'], $data['month'], $data['day'], date("Y") + 1);
  190. break;
  191. default:
  192. $cycle_time = 0;
  193. break;
  194. }
  195. return $cycle_time;
  196. }
  197. /**
  198. * 接口执行执行任务
  199. * @throws \think\db\exception\DataNotFoundException
  200. * @throws \think\db\exception\DbException
  201. * @throws \think\db\exception\ModelNotFoundException
  202. * @author 吴汐
  203. * @email 442384644@qq.com
  204. * @date 2023/02/17
  205. */
  206. public function crontabApiRun()
  207. {
  208. $crontabRunServices = app()->make(CrontabRunServices::class);
  209. $time = time();
  210. file_put_contents(root_path() . 'runtime/.timer', $time); //检测定时任务是否正常
  211. $list = $this->dao->selectList(['is_open' => 1, 'is_del' => 0])->toArray();
  212. foreach ($list as $item) {
  213. if ($item['next_execution_time'] < $time) {
  214. //转化小驼峰方法名
  215. $functionName = Str::camel($item['mark']);
  216. //执行定时任务
  217. $crontabRunServices->$functionName();
  218. //写入本次执行时间和下次执行时间
  219. $this->dao->update(['mark' => $item['mark']], ['last_execution_time' => $time, 'next_execution_time' => $this->getTimerCycleTime($item)]);
  220. }
  221. }
  222. }
  223. /**
  224. * 运行定时任务
  225. *
  226. * @param object $task 任务对象
  227. * @return void
  228. */
  229. public function crontabCommandRun($task)
  230. {
  231. file_put_contents(root_path() . 'runtime/.timer', time());
  232. // 获取 CrontabRunServices 实例
  233. $crontabRunServices = app()->make(CrontabRunServices::class);
  234. // 创建一个每秒钟执行一次的定时任务
  235. new Crontab('*/1 * * * * *', function () use ($task, $crontabRunServices) {
  236. // 写入时间戳,用于检测定时任务是否正常执行
  237. $timerTime = file_get_contents(root_path() . 'runtime/.timer');
  238. if ($timerTime < (time() - 60)) {
  239. file_put_contents(root_path() . 'runtime/.timer', time());
  240. }
  241. // 从缓存中获取定时任务列表
  242. $list = Cache::get('crontabCache');
  243. if (!$list) {
  244. $list = $this->dao->selectList([])->toArray();
  245. Cache::set('crontabCache', $list);
  246. }
  247. // 遍历定时任务列表
  248. foreach ($list as &$item) {
  249. // 获取函数名
  250. $functionName = Str::camel($item['mark']);
  251. if ($functionName == 'customTimer') {
  252. $functionName = 'customTimer_' . $item['id'];
  253. }
  254. // 如果更新时间不存在,则将其设置为添加时间
  255. $item['update_time'] = $item['update_time'] ?: $item['add_time'];
  256. // 如果任务已经被执行过,则跳过此次循环
  257. if (isset($task->task_ids[$functionName]) && $task->task_ids[$functionName]['time'] == $item['update_time']) {
  258. continue;
  259. }
  260. // 获取定时器字符串
  261. $timeStr = $item['timeStr'] != '' ? $item['timeStr'] : $this->getTimerStr($item);
  262. // 获取自定义代码
  263. $customCode = json_decode($item['customCode']);
  264. // 如果任务已经被执行过,并且当前时间和上次执行时间不同,则销毁之前的定时任务
  265. if (isset($task->task_ids[$functionName]) && $task->task_ids[$functionName]['time'] != $item['update_time'] && isset($task->task_ids[$functionName]['crontab']) && $task->task_ids[$functionName]['crontab'] instanceof Crontab) {
  266. $task->task_ids[$functionName]['crontab']->destroy();
  267. unset($task->task_ids[$functionName]);
  268. }
  269. // 如果任务是开启状态,则创建一个新的定时任务
  270. if ($item['is_open'] == 1) {
  271. $crontab = new Crontab($timeStr, function () use ($crontabRunServices, $functionName, $customCode) {
  272. // 根据函数名调用相应的方法
  273. if (strpos($functionName, 'customTimer_') === 0) {
  274. $crontabRunServices->customTimer($customCode);
  275. } else {
  276. $crontabRunServices->$functionName();
  277. }
  278. });
  279. $task->task_ids[$functionName] = ['crontab' => $crontab, 'time' => $item['update_time']];
  280. }
  281. }
  282. });
  283. }
  284. /**
  285. * 获取定时任务时间表达式
  286. * 0 1 2 3 4 5
  287. * | | | | | |
  288. * | | | | | +------ day of week (0 - 6) (Sunday=0)
  289. * | | | | +------ month (1 - 12)
  290. * | | | +-------- day of month (1 - 31)
  291. * | | +---------- hour (0 - 23)
  292. * | +------------ min (0 - 59)
  293. * +-------------- sec (0-59)[可省略,如果没有0位,则最小时间粒度是分钟]
  294. * @param $data
  295. * @return string
  296. */
  297. public function getTimerStr($data): string
  298. {
  299. $timeStr = '';
  300. switch ($data['type']) {
  301. case 1:// 每隔几秒
  302. $timeStr = '*/' . $data['second'] . ' * * * * *';
  303. break;
  304. case 2:// 每隔几分
  305. $timeStr = '0 */' . $data['minute'] . ' * * * *';
  306. break;
  307. case 3:// 每隔几时第几分钟执行
  308. $timeStr = '0 ' . $data['minute'] . ' */' . $data['hour'] . ' * * *';
  309. break;
  310. case 4:// 每隔几日第几小时第几分钟执行
  311. $timeStr = '0 ' . $data['minute'] . ' ' . $data['hour'] . ' */' . $data['day'] . ' * *';
  312. break;
  313. case 5:// 每日几时几分几秒
  314. $timeStr = $data['second'] . ' ' . $data['minute'] . ' ' . $data['hour'] . ' * * *';
  315. break;
  316. case 6:// 每周周几几时几分几秒
  317. $timeStr = $data['second'] . ' ' . $data['minute'] . ' ' . $data['hour'] . ' * * ' . ($data['week'] == 7 ? 0 : $data['week']);
  318. break;
  319. case 7:// 每月几日几时几分几秒
  320. $timeStr = $data['second'] . ' ' . $data['minute'] . ' ' . $data['hour'] . ' ' . $data['day'] . ' * *';
  321. break;
  322. case 8:// 每年几月几日几时几分几秒
  323. $timeStr = $data['second'] . ' ' . $data['minute'] . ' ' . $data['hour'] . ' ' . $data['day'] . ' ' . $data['month'] . ' *';
  324. break;
  325. }
  326. return $timeStr;
  327. }
  328. }