1. <?php
  2. /**
  3. * Flushes output for timestamps in short-lived tasks.
  4. *
  5. * This code is designed for situations where asynchronous processing
  6. * is not feasible and immediate output is desired.
  7. */
  8. /**
  9. * Function to flush output.
  10. */
  11. function flush_output() {
  12. ob_flush(); // Flush output buffer.
  13. fflush(stdout); // Flush standard output.
  14. fflush(stderr); // Flush standard error.
  15. }
  16. /**
  17. * Example usage:
  18. *
  19. * This function is meant to be called at key points in your task.
  20. * After each timestamp/output you want to see immediately.
  21. */
  22. function example_task() {
  23. $timestamp = date('Y-m-d H:i:s');
  24. echo "Task started: " . $timestamp . "\n";
  25. flush_output(); // Flush after starting message.
  26. // Simulate some work
  27. usleep(500000); // 0.5 seconds
  28. $timestamp = date('Y-m-d H:i:s');
  29. echo "Task processing: " . $timestamp . "\n";
  30. flush_output(); // Flush after processing message.
  31. // Simulate more work
  32. usleep(750000); // 0.75 seconds
  33. $timestamp = date('Y-m-d H:i:s');
  34. echo "Task completed: " . $timestamp . "\n";
  35. flush_output(); // Flush after completion message.
  36. }
  37. // call the example task
  38. example_task();
  39. ?>

Add your comment