SystemCrontabServices.php 15 KB

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