Vote.php 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119
  1. <?php
  2. namespace crmeb\utils;
  3. use crmeb\traits\LogicTrait;
  4. use think\facade\Queue as QueueJob;
  5. /**
  6. * Class Vote
  7. * @package crmeb\utils
  8. * @method $this setJobClassName(string $jobClassName); 设置任务类名
  9. * @method $this setQueue(string $queue); 设置任务名
  10. * @method $this setDelay(int $delay); 设置延迟时间
  11. * @method $this setJobData(array $jobData); 设置任务参数
  12. */
  13. class Vote
  14. {
  15. use LogicTrait;
  16. /**
  17. * 任务类名
  18. * @var string
  19. */
  20. protected $jobClassName = \crmeb\jobs\VoteJob::class;
  21. /**
  22. * 多任务
  23. * @var null
  24. */
  25. protected $task = null;
  26. /**
  27. * 任务参数
  28. * @var array
  29. */
  30. protected $jobData = [
  31. 'beforeMethod' => 'doBeforeMethod', //默认任务执行前执行的方法
  32. 'method' => 'doDefaultJod', //默认任务执行方法
  33. 'data' => null, //执行任务需要的参数
  34. 'errorTimes' => 3, //任务执行错误最大次数
  35. 'release' => 0,//延迟执行秒数
  36. ];
  37. /**
  38. * 任务名称
  39. * @var string
  40. */
  41. protected $queue = 'Vote';
  42. /**
  43. * 延迟执行秒数
  44. * @var int
  45. */
  46. protected $delay = 0;
  47. /**
  48. * 规则
  49. * @var array
  50. */
  51. protected $propsRule = [
  52. 'jobClassName' => null,
  53. 'queue' => null,
  54. 'delay' => null,
  55. 'jobData' => null,
  56. ];
  57. /**
  58. * 创建定时执行任务
  59. * @param $data
  60. * @return mixed
  61. */
  62. public function push($data = null)
  63. {
  64. $this->merge($data);
  65. return QueueJob::push($this->jobClassName, $this->jobData, $this->queue);
  66. }
  67. /**
  68. * 创建延迟执行任务
  69. * @param null $data
  70. * @return mixed
  71. */
  72. public function later($data = null)
  73. {
  74. $this->merge($data);
  75. return QueueJob::later($this->delay, $this->jobClassName, $this->jobData, $this->queue);
  76. }
  77. /**
  78. * 合并处理参数
  79. * @param $data
  80. */
  81. protected function merge($data)
  82. {
  83. if ($data) {
  84. $this->jobData['data'] = $data;
  85. }
  86. if ($this->delay && !$this->jobData['release']) {
  87. $this->jobData['release'] = $this->delay;
  88. }
  89. $this->jobClassName = $this->task ? $this->jobClassName . '@' . $this->task : $this->jobClassName;
  90. }
  91. /**
  92. * 创建任务
  93. * @param null $data
  94. * @return mixed
  95. */
  96. public static function create($data = null)
  97. {
  98. $instance = self::instance();
  99. if ($instance->delay) {
  100. return $instance->later($data);
  101. } else {
  102. return $instance->push($data);
  103. }
  104. }
  105. }