<?php
/**
* Schedules the execution of an array of functions/closures with default values.
*
* @param array $scheduled_functions An array of arrays, where each inner array contains:
* - 'name': The name of the function/closure to execute.
* - 'args': An array of default arguments.
* - 'delay': The delay in seconds before execution.
* @return void
*/
function schedule_functions(array $scheduled_functions): void
{
foreach ($scheduled_functions as $function_data) {
$function_name = $function_data['name'];
$default_args = $function_data['args'];
$delay = $function_data['delay'];
// Ensure the function exists
if (!function_exists($function_name)) {
error_log("Function '$function_name' not found.");
continue;
}
// Create a wrapper function to capture the default arguments
$wrapper_function = function () use ($function_name, ...$default_args) {
call_user_func($function_name, ...$default_args);
};
// Use `usleep` for precise delays (microseconds)
$sleep_time = (int)($delay * 1000000);
usleep($sleep_time);
// Execute the wrapped function
$wrapper_function();
}
}
// Example Usage (Sandbox)
if (PHP_SAPI === 'cli') { //Only run in CLI
// Define some example functions
function sandbox_function1(string $message, int $number): void
{
echo "Function 1 executed: Message = " . $message . ", Number = " . $number . PHP_EOL;
}
function sandbox_function2(float $value): void
{
echo "Function 2 executed: Value = " . $value . PHP_EOL;
}
// Schedule the functions
$scheduled_tasks = [
['name' => 'sandbox_function1', 'args' => ['Hello', 123], 'delay' => 2], // Execute after 2 seconds
['name' => 'sandbox_function2', 'args' => [3.14], 'delay' => 1], // Execute after 1 second.
['name' => 'nonexistent_function', 'args' => [], 'delay' => 3], // This will log an error
];
schedule_functions($scheduled_tasks);
}
?>
Add your comment