1. <?php
  2. /**
  3. * Schedules the execution of an array of functions/closures with default values.
  4. *
  5. * @param array $scheduled_functions An array of arrays, where each inner array contains:
  6. * - 'name': The name of the function/closure to execute.
  7. * - 'args': An array of default arguments.
  8. * - 'delay': The delay in seconds before execution.
  9. * @return void
  10. */
  11. function schedule_functions(array $scheduled_functions): void
  12. {
  13. foreach ($scheduled_functions as $function_data) {
  14. $function_name = $function_data['name'];
  15. $default_args = $function_data['args'];
  16. $delay = $function_data['delay'];
  17. // Ensure the function exists
  18. if (!function_exists($function_name)) {
  19. error_log("Function '$function_name' not found.");
  20. continue;
  21. }
  22. // Create a wrapper function to capture the default arguments
  23. $wrapper_function = function () use ($function_name, ...$default_args) {
  24. call_user_func($function_name, ...$default_args);
  25. };
  26. // Use `usleep` for precise delays (microseconds)
  27. $sleep_time = (int)($delay * 1000000);
  28. usleep($sleep_time);
  29. // Execute the wrapped function
  30. $wrapper_function();
  31. }
  32. }
  33. // Example Usage (Sandbox)
  34. if (PHP_SAPI === 'cli') { //Only run in CLI
  35. // Define some example functions
  36. function sandbox_function1(string $message, int $number): void
  37. {
  38. echo "Function 1 executed: Message = " . $message . ", Number = " . $number . PHP_EOL;
  39. }
  40. function sandbox_function2(float $value): void
  41. {
  42. echo "Function 2 executed: Value = " . $value . PHP_EOL;
  43. }
  44. // Schedule the functions
  45. $scheduled_tasks = [
  46. ['name' => 'sandbox_function1', 'args' => ['Hello', 123], 'delay' => 2], // Execute after 2 seconds
  47. ['name' => 'sandbox_function2', 'args' => [3.14], 'delay' => 1], // Execute after 1 second.
  48. ['name' => 'nonexistent_function', 'args' => [], 'delay' => 3], // This will log an error
  49. ];
  50. schedule_functions($scheduled_tasks);
  51. }
  52. ?>

Add your comment