SystemCrontabServices.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345
  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(['is_open' => 1, 'is_del' => 0])->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(['is_open' => 1, 'is_del' => 0])->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(['is_open' => 1, 'is_del' => 0])->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. if (strpos($functionName, 'customTimer') === 0) {
  218. $crontabRunServices->customTimer(json_decode($item['customCode']));
  219. } else {
  220. $crontabRunServices->$functionName();
  221. }
  222. //写入本次执行时间和下次执行时间
  223. $this->dao->update(['mark' => $item['mark']], ['last_execution_time' => $time, 'next_execution_time' => $this->getTimerCycleTime($item)]);
  224. }
  225. }
  226. }
  227. /**
  228. * 运行定时任务
  229. *
  230. * @param object $task 任务对象
  231. * @return void
  232. */
  233. public function crontabCommandRun($task)
  234. {
  235. file_put_contents(root_path() . 'runtime/.timer', time());
  236. // 获取 CrontabRunServices 实例
  237. $crontabRunServices = app()->make(CrontabRunServices::class);
  238. // 创建一个每秒钟执行一次的定时任务
  239. new Crontab('*/1 * * * * *', function () use ($task, $crontabRunServices) {
  240. // 写入时间戳,用于检测定时任务是否正常执行
  241. $timerTime = file_get_contents(root_path() . 'runtime/.timer');
  242. if ($timerTime < (time() - 60)) {
  243. file_put_contents(root_path() . 'runtime/.timer', time());
  244. }
  245. // 从缓存中获取定时任务列表
  246. $list = Cache::get('crontabCache');
  247. if (!$list) {
  248. $list = $this->dao->selectList(['is_open' => 1, 'is_del' => 0])->toArray();
  249. Cache::set('crontabCache', $list);
  250. }
  251. // 遍历定时任务列表
  252. foreach ($list as &$item) {
  253. // 获取函数名
  254. $functionName = Str::camel($item['mark']);
  255. if ($functionName == 'customTimer') {
  256. $functionName = 'customTimer_' . $item['id'];
  257. }
  258. // 如果更新时间不存在,则将其设置为添加时间
  259. $item['update_time'] = $item['update_time'] ?: $item['add_time'];
  260. // 如果任务已经被执行过,则跳过此次循环
  261. if (isset($task->task_ids[$functionName]) && $task->task_ids[$functionName]['time'] == $item['update_time']) {
  262. continue;
  263. }
  264. // 获取定时器字符串
  265. $timeStr = $item['timeStr'] != '' ? $item['timeStr'] : $this->getTimerStr($item);
  266. // 获取自定义代码
  267. $customCode = json_decode($item['customCode']);
  268. // 如果任务已经被执行过,并且当前时间和上次执行时间不同,则销毁之前的定时任务
  269. 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) {
  270. $task->task_ids[$functionName]['crontab']->destroy();
  271. unset($task->task_ids[$functionName]);
  272. }
  273. // 如果任务是开启状态,则创建一个新的定时任务
  274. if ($item['is_open'] == 1) {
  275. $crontab = new Crontab($timeStr, function () use ($crontabRunServices, $functionName, $customCode) {
  276. // 根据函数名调用相应的方法
  277. if (strpos($functionName, 'customTimer_') === 0) {
  278. $crontabRunServices->customTimer($customCode);
  279. } else {
  280. $crontabRunServices->$functionName();
  281. }
  282. });
  283. $task->task_ids[$functionName] = ['crontab' => $crontab, 'time' => $item['update_time']];
  284. }
  285. }
  286. });
  287. }
  288. /**
  289. * 获取定时任务时间表达式
  290. * 0 1 2 3 4 5
  291. * | | | | | |
  292. * | | | | | +------ day of week (0 - 6) (Sunday=0)
  293. * | | | | +------ month (1 - 12)
  294. * | | | +-------- day of month (1 - 31)
  295. * | | +---------- hour (0 - 23)
  296. * | +------------ min (0 - 59)
  297. * +-------------- sec (0-59)[可省略,如果没有0位,则最小时间粒度是分钟]
  298. * @param $data
  299. * @return string
  300. */
  301. public function getTimerStr($data): string
  302. {
  303. $timeStr = '';
  304. switch ($data['type']) {
  305. case 1:// 每隔几秒
  306. $timeStr = '*/' . $data['second'] . ' * * * * *';
  307. break;
  308. case 2:// 每隔几分
  309. $timeStr = '0 */' . $data['minute'] . ' * * * *';
  310. break;
  311. case 3:// 每隔几时第几分钟执行
  312. $timeStr = '0 ' . $data['minute'] . ' */' . $data['hour'] . ' * * *';
  313. break;
  314. case 4:// 每隔几日第几小时第几分钟执行
  315. $timeStr = '0 ' . $data['minute'] . ' ' . $data['hour'] . ' */' . $data['day'] . ' * *';
  316. break;
  317. case 5:// 每日几时几分几秒
  318. $timeStr = $data['second'] . ' ' . $data['minute'] . ' ' . $data['hour'] . ' * * *';
  319. break;
  320. case 6:// 每周周几几时几分几秒
  321. $timeStr = $data['second'] . ' ' . $data['minute'] . ' ' . $data['hour'] . ' * * ' . ($data['week'] == 7 ? 0 : $data['week']);
  322. break;
  323. case 7:// 每月几日几时几分几秒
  324. $timeStr = $data['second'] . ' ' . $data['minute'] . ' ' . $data['hour'] . ' ' . $data['day'] . ' * *';
  325. break;
  326. case 8:// 每年几月几日几时几分几秒
  327. $timeStr = $data['second'] . ' ' . $data['minute'] . ' ' . $data['hour'] . ' ' . $data['day'] . ' ' . $data['month'] . ' *';
  328. break;
  329. }
  330. return $timeStr;
  331. }
  332. }