1. <?php
  2. class LogQueue {
  3. private $queue = [];
  4. private $filePath = 'log_tasks.txt';
  5. public function enqueue(string $task): void {
  6. // Add task to the queue
  7. $this->queue[] = $task;
  8. $this->saveQueue();
  9. }
  10. public function dequeue(): string|null {
  11. // Remove and return the first task from the queue
  12. if (empty($this->queue)) {
  13. return null;
  14. }
  15. return array_shift($this->queue);
  16. }
  17. private function saveQueue(): void {
  18. // Save the queue to a file
  19. file_put_contents($this->filePath, implode("\n", $this->queue));
  20. }
  21. private function loadQueue(): void {
  22. // Load the queue from a file
  23. if (file_exists($this->filePath)) {
  24. $queueData = file($this->filePath, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
  25. $this->queue = $queueData ? array_reverse($queueData) : []; // Reverse to maintain order
  26. }
  27. }
  28. public function run(): void {
  29. // Process tasks from the queue
  30. $this->loadQueue();
  31. while (true) {
  32. $task = $this->dequeue();
  33. if ($task) {
  34. try {
  35. // Simulate log file processing
  36. echo "Processing task: $task\n";
  37. // Add your log file processing logic here
  38. usleep(500000); // Simulate work
  39. } catch (Exception $e) {
  40. echo "Error processing task '$task': " . $e->getMessage() . "\n";
  41. }
  42. } else {
  43. // Queue is empty, wait for a bit
  44. usleep(1000000);
  45. }
  46. }
  47. }
  48. }
  49. // Example Usage:
  50. $queue = new LogQueue();
  51. $queue->enqueue('process_file_1.log');
  52. $queue->enqueue('process_file_2.log');
  53. $queue->enqueue('process_file_3.log');
  54. // Start the queue processor in a separate thread/process
  55. $queue->run();
  56. ?>

Add your comment