Queue.php 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. <?php
  2. namespace easyTask;
  3. /**
  4. * Class Queue
  5. * @package easyTask
  6. */
  7. class Queue
  8. {
  9. /**
  10. * 进程锁
  11. * @var Lock
  12. */
  13. private $lock;
  14. /**
  15. * 队列文件
  16. * @var string
  17. */
  18. private $queFile;
  19. /**
  20. * 构造函数
  21. * @param string $name
  22. * @throws
  23. */
  24. public function __construct($name = 'queue')
  25. {
  26. //创建进程锁
  27. $this->lock = new Lock($name);
  28. //创建队列文件
  29. $path = Helper::getQuePath();
  30. $file = $path . '%s.dat';
  31. $this->queFile = sprintf($file, md5($name));
  32. if (!file_exists($this->queFile))
  33. {
  34. if (!file_put_contents($this->queFile, '[]', LOCK_EX))
  35. {
  36. Helper::showError('crate queFile failed,please try again');
  37. }
  38. }
  39. }
  40. /**
  41. * 向队列投递数据
  42. * @param string $item
  43. */
  44. public function push($item)
  45. {
  46. $this->lock->execute(function () use ($item) {
  47. //read
  48. $content = file_get_contents($this->queFile);
  49. $queue_data = $content ? json_decode($content, true) : [];
  50. $queue_data = is_array($queue_data) ? $queue_data : [];
  51. //write
  52. array_push($queue_data, $item);
  53. if (!file_put_contents($this->queFile, json_encode($queue_data)))
  54. {
  55. Helper::showError('failed to save data to queue file');
  56. }
  57. });
  58. }
  59. /**
  60. * 从队列弹出数据
  61. * @return string|null
  62. */
  63. public function shift()
  64. {
  65. return $this->lock->execute(function () {
  66. //read
  67. $content = file_get_contents($this->queFile);
  68. $queue_data = $content ? json_decode($content, true) : [];
  69. $queue_data = is_array($queue_data) ? $queue_data : [];
  70. //shift+write
  71. $value = array_shift($queue_data);
  72. if (!file_put_contents($this->queFile, json_encode($queue_data)))
  73. {
  74. Helper::showError('failed to save data to queue file');
  75. }
  76. return $value;
  77. });
  78. }
  79. }