BaseTimer.php 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | 萤火商城系统 [ 致力于通过产品和服务,帮助商家高效化开拓市场 ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2017~2025 https://www.yiovo.com All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed 这不是一个自由软件,不允许对程序代码以任何形式任何目的的再发行
  8. // +----------------------------------------------------------------------
  9. // | Author: 萤火科技 <admin@yiovo.com>
  10. // +----------------------------------------------------------------------
  11. declare (strict_types=1);
  12. namespace cores;
  13. use think\facade\Cache;
  14. /**
  15. * 定时任务监听器
  16. * Class BaseTimer
  17. * @package app\timer\controller
  18. */
  19. class BaseTimer
  20. {
  21. // 当前任务唯一标识 (由子类定义)
  22. protected string $taskKey = '';
  23. // 任务执行间隔时长 (单位:秒)
  24. protected int $taskExpire = 60 * 30;
  25. // 当前商城ID
  26. protected int $storeId;
  27. /**
  28. * 定时执行任务 (支持自定义时间间隔)
  29. * @param int $storeId 商城ID
  30. * @param string $key 任务标识
  31. * @param int|null $expire 定时间隔 (单位秒)
  32. * @param callable $callback 回调方法
  33. * @return mixed
  34. */
  35. protected final function setInterval(int $storeId, string $key, int $expire, callable $callback)
  36. {
  37. if (!$this->hasTaskId($storeId, $key)) {
  38. $this->setTaskId($storeId, $key, $expire);
  39. return call_user_func($callback);
  40. }
  41. return null;
  42. }
  43. /**
  44. * 获取任务ID
  45. * @param int $storeId 商城ID
  46. * @param string $key 任务标识
  47. * @return bool
  48. */
  49. protected final function hasTaskId(int $storeId, string $key): bool
  50. {
  51. return Cache::has("Listener:$storeId:$key");
  52. }
  53. /**
  54. * 设置任务ID
  55. * 用于实现定时任务的间隔时间, 如果任务ID存在并未过期, 则不执行任务
  56. * @param int $storeId 商城ID
  57. * @param string $key 任务标识
  58. * @param int $expire 定时间隔 (单位:秒)
  59. * @return bool
  60. */
  61. protected final function setTaskId(int $storeId, string $key, int $expire = 60): bool
  62. {
  63. return Cache::set("Listener:$storeId:$key", true, $expire);
  64. }
  65. /**
  66. * 任务处理 (cores)
  67. * @param array $param 参数 (storeId)
  68. * @param callable $callback 回调方法
  69. * @return mixed|null
  70. */
  71. protected final function handleTask(array $param, callable $callback)
  72. {
  73. ['storeId' => $this->storeId] = $param;
  74. return $this->setInterval($this->storeId, $this->taskKey, $this->taskExpire, function () use ($callback) {
  75. echo $this->taskKey . PHP_EOL;
  76. return call_user_func($callback);
  77. });
  78. }
  79. }