1. <?php
  2. /**
  3. * Flushes output from task queues with a timeout.
  4. *
  5. * @param array $queue An array representing the task queue. Each element
  6. * should be an array with 'data' and 'timeout' keys.
  7. * 'data' is the data to be flushed.
  8. * 'timeout' is the timeout in seconds.
  9. * @return bool True on success, false on failure.
  10. */
  11. function flushTaskQueue(array $queue): bool
  12. {
  13. $startTime = time();
  14. $success = true;
  15. foreach ($queue as $task) {
  16. $data = $task['data'];
  17. $timeout = $task['timeout'];
  18. if (empty($data)) {
  19. continue; // Skip tasks with empty data.
  20. }
  21. $output = fopen('php://output', 'w'); // Open output stream for writing.
  22. if ($output === false) {
  23. error_log("Error opening output stream for flushing task: " . json_encode($task));
  24. $success = false;
  25. continue;
  26. }
  27. $start = time();
  28. // Flush output with timeout.
  29. try {
  30. flush($output);
  31. // Wait for the timeout.
  32. while (time() - $start < $timeout) {
  33. usleep(1000); // Sleep for 1 millisecond.
  34. }
  35. if (time() - $start >= $timeout) {
  36. error_log("Task flushed beyond timeout: " . json_encode($task));
  37. $success = false;
  38. }
  39. } catch (Exception $e) {
  40. error_log("Error flushing task: " . json_encode($task) . ". Exception: " . $e->getMessage());
  41. $success = false;
  42. }
  43. fclose($output);
  44. }
  45. return $success;
  46. }

Add your comment