<?php
/**
* Flushes output from task queues with a timeout.
*
* @param array $queue An array representing the task queue. Each element
* should be an array with 'data' and 'timeout' keys.
* 'data' is the data to be flushed.
* 'timeout' is the timeout in seconds.
* @return bool True on success, false on failure.
*/
function flushTaskQueue(array $queue): bool
{
$startTime = time();
$success = true;
foreach ($queue as $task) {
$data = $task['data'];
$timeout = $task['timeout'];
if (empty($data)) {
continue; // Skip tasks with empty data.
}
$output = fopen('php://output', 'w'); // Open output stream for writing.
if ($output === false) {
error_log("Error opening output stream for flushing task: " . json_encode($task));
$success = false;
continue;
}
$start = time();
// Flush output with timeout.
try {
flush($output);
// Wait for the timeout.
while (time() - $start < $timeout) {
usleep(1000); // Sleep for 1 millisecond.
}
if (time() - $start >= $timeout) {
error_log("Task flushed beyond timeout: " . json_encode($task));
$success = false;
}
} catch (Exception $e) {
error_log("Error flushing task: " . json_encode($task) . ". Exception: " . $e->getMessage());
$success = false;
}
fclose($output);
}
return $success;
}
Add your comment