<?php
class LogQueue {
private $queue = [];
private $filePath = 'log_tasks.txt';
public function enqueue(string $task): void {
// Add task to the queue
$this->queue[] = $task;
$this->saveQueue();
}
public function dequeue(): string|null {
// Remove and return the first task from the queue
if (empty($this->queue)) {
return null;
}
return array_shift($this->queue);
}
private function saveQueue(): void {
// Save the queue to a file
file_put_contents($this->filePath, implode("\n", $this->queue));
}
private function loadQueue(): void {
// Load the queue from a file
if (file_exists($this->filePath)) {
$queueData = file($this->filePath, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$this->queue = $queueData ? array_reverse($queueData) : []; // Reverse to maintain order
}
}
public function run(): void {
// Process tasks from the queue
$this->loadQueue();
while (true) {
$task = $this->dequeue();
if ($task) {
try {
// Simulate log file processing
echo "Processing task: $task\n";
// Add your log file processing logic here
usleep(500000); // Simulate work
} catch (Exception $e) {
echo "Error processing task '$task': " . $e->getMessage() . "\n";
}
} else {
// Queue is empty, wait for a bit
usleep(1000000);
}
}
}
}
// Example Usage:
$queue = new LogQueue();
$queue->enqueue('process_file_1.log');
$queue->enqueue('process_file_2.log');
$queue->enqueue('process_file_3.log');
// Start the queue processor in a separate thread/process
$queue->run();
?>
Add your comment