1. <?php
  2. use Firebase\Functional\Functions\Functions;
  3. use Firebase\Functional\Functions\Function;
  4. use Firebase\Functional\Functions\FunctionOptions;
  5. use Firebase\Functional\Functions\FunctionRunner;
  6. use Firebase\Functional\Functions\RetryOptions;
  7. /**
  8. * Schedules execution of JSON payloads with retry logic.
  9. *
  10. * @param array $payload The JSON payload to execute.
  11. * @param string $function_name The name of the function to execute.
  12. * @param string $function_path The path to the function file.
  13. * @param int $retries The number of retries.
  14. * @param int $delay The delay between retries in seconds.
  15. * @return bool True on success, false on failure.
  16. */
  17. function scheduleAndExecute(array $payload, string $function_name, string $function_path, int $retries = 3, int $delay = 5): bool
  18. {
  19. try {
  20. // Define retry options
  21. $retry_options = new RetryOptions([
  22. 'maxAttempts' => $retries,
  23. 'delayBetweenAttempts' => $delay,
  24. ]);
  25. // Create a function runner
  26. $function_runner = new FunctionRunner();
  27. // Execute the function with retry logic
  28. $result = $function_runner->run(
  29. $function_name,
  30. $function_path,
  31. $payload,
  32. $retry_options
  33. );
  34. // Check if the function execution was successful
  35. if ($result === true) {
  36. return true;
  37. } else {
  38. return false;
  39. }
  40. } catch (\Exception $e) {
  41. // Log the error
  42. error_log("Error executing function: " . $e->getMessage());
  43. return false;
  44. }
  45. }
  46. /**
  47. * Example Usage (Illustrative)
  48. */
  49. // Sample payload
  50. $data = ['key1' => 'value1', 'key2' => 'value2'];
  51. // Function details
  52. $functionName = 'my_function';
  53. $functionPath = 'path/to/my_function.php'; // Replace with your function path
  54. // Schedule and execute the function
  55. $success = scheduleAndExecute($data, $functionName, $functionPath);
  56. if ($success) {
  57. echo "Function executed successfully.\n";
  58. } else {
  59. echo "Function execution failed.\n";
  60. }
  61. ?>

Add your comment