<?php
class TaskQueue {
private $queue = [];
private $running = false;
public function __construct() {}
public function enqueue(callable $task, array $data = []) {
// Enqueue the task and its data
$this->queue[] = [
'task' => $task,
'data' => $data,
];
}
public function run() {
// Start the worker process
$this->running = true;
while ($this->running && !empty($this->queue)) {
$taskInfo = array_shift($this->queue); // Get the next task
$task = $taskInfo['task'];
$data = $taskInfo['data'];
try {
// Execute the task
$task($data);
} catch (Exception $e) {
error_log("Task failed: " . $e->getMessage()); // Log errors
}
}
$this->running = false;
}
public function stop() {
// Stop the worker process
$this->running = false;
}
}
//Example Usage (Development - requires manual execution)
//Define a dummy HTTP request task
function simulateHttpRequest(array $data) {
//Simulate an HTTP request using the provided data.
echo "Simulating HTTP request with data: " . print_r($data, true) . "\n";
//In a real implementation, you'd use curl or similar to make the request
}
// Create a task queue instance
$queue = new TaskQueue();
// Enqueue some tasks
$queue->enqueue(function ($data) { simulateHttpRequest($data); }, ['url' => 'https://example.com']);
$queue->enqueue(function ($data) { simulateHttpRequest($data); }, ['url' => 'https://another.example.com']);
// Start the queue worker
$queue->run();
//Stop the queue worker.
$queue->stop();
?>
Add your comment