1. <?php
  2. class TaskQueue {
  3. private $queue = [];
  4. private $running = false;
  5. public function __construct() {}
  6. public function enqueue(callable $task, array $data = []) {
  7. // Enqueue the task and its data
  8. $this->queue[] = [
  9. 'task' => $task,
  10. 'data' => $data,
  11. ];
  12. }
  13. public function run() {
  14. // Start the worker process
  15. $this->running = true;
  16. while ($this->running && !empty($this->queue)) {
  17. $taskInfo = array_shift($this->queue); // Get the next task
  18. $task = $taskInfo['task'];
  19. $data = $taskInfo['data'];
  20. try {
  21. // Execute the task
  22. $task($data);
  23. } catch (Exception $e) {
  24. error_log("Task failed: " . $e->getMessage()); // Log errors
  25. }
  26. }
  27. $this->running = false;
  28. }
  29. public function stop() {
  30. // Stop the worker process
  31. $this->running = false;
  32. }
  33. }
  34. //Example Usage (Development - requires manual execution)
  35. //Define a dummy HTTP request task
  36. function simulateHttpRequest(array $data) {
  37. //Simulate an HTTP request using the provided data.
  38. echo "Simulating HTTP request with data: " . print_r($data, true) . "\n";
  39. //In a real implementation, you'd use curl or similar to make the request
  40. }
  41. // Create a task queue instance
  42. $queue = new TaskQueue();
  43. // Enqueue some tasks
  44. $queue->enqueue(function ($data) { simulateHttpRequest($data); }, ['url' => 'https://example.com']);
  45. $queue->enqueue(function ($data) { simulateHttpRequest($data); }, ['url' => 'https://another.example.com']);
  46. // Start the queue worker
  47. $queue->run();
  48. //Stop the queue worker.
  49. $queue->stop();
  50. ?>

Add your comment