Controller.php 2.0 KB

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