1. <?php
  2. /**
  3. * Timestamp Script Executor - Optimized for Batch Processing & Low Memory
  4. */
  5. class TimestampExecutor
  6. {
  7. private $script_paths = [];
  8. private $output_dir = '';
  9. public function __construct(array $script_paths, string $output_dir = '')
  10. {
  11. $this->script_paths = $script_paths;
  12. $this->output_dir = rtrim($output_dir, '/'); // Ensure no trailing slash
  13. }
  14. /**
  15. * Executes timestamp scripts in batches.
  16. *
  17. * @param int $batch_size The number of scripts to execute in each batch.
  18. * @return array An array of execution results (success/failure).
  19. */
  20. public function executeScripts(int $batch_size = 5)
  21. {
  22. $results = [];
  23. $script_count = count($this->script_paths);
  24. if ($script_count === 0) {
  25. return $results; // Return empty array if no scripts
  26. }
  27. for ($i = 0; $i < $script_count; $i += $batch_size) {
  28. $batch = array_slice($this->script_paths, $i, $batch_size);
  29. $batch_results = [];
  30. foreach ($batch as $script_path) {
  31. $result = $this->executeScript($script_path);
  32. $batch_results[] = $result;
  33. }
  34. $results = array_merge($results, $batch_results);
  35. }
  36. return $results;
  37. }
  38. /**
  39. * Executes a single timestamp script.
  40. *
  41. * @param string $script_path The path to the timestamp script.
  42. * @return string 'success' or 'failure'
  43. */
  44. private function executeScript(string $script_path): string
  45. {
  46. $command = "php " . escapeshellarg($script_path); //Sanitize the script path
  47. $output = [];
  48. $return_var = 0;
  49. exec($command, $output, $return_var);
  50. if ($return_var === 0) {
  51. return 'success';
  52. } else {
  53. return 'failure';
  54. }
  55. }
  56. /**
  57. * Writes output to files based on script results.
  58. *
  59. * @param array $results Array of execution results (success/failure).
  60. */
  61. public function writeResults(array $results): void
  62. {
  63. if (empty($results)) {
  64. return;
  65. }
  66. $log_file = $this->output_dir . '/timestamp_execution.log';
  67. file_put_contents($log_file, date('Y-m-d H:i:s') . " - Timestamp Execution Log\n");
  68. foreach ($results as $result) {
  69. file_put_contents($log_file, date('Y-m-d H:i:s') . " - " . $result . "\n", FILE_APPEND);
  70. }
  71. }
  72. }
  73. // Example Usage:
  74. $scripts = [
  75. 'script1.php',
  76. 'script2.php',
  77. 'script3.php',
  78. 'script4.php',
  79. 'script5.php',
  80. 'script6.php',
  81. 'script7.php',
  82. 'script8.php',
  83. 'script9.php',
  84. 'script10.php',
  85. ];
  86. $executor = new TimestampExecutor($scripts, '/path/to/output');
  87. $results = $executor->executeScripts(3); // Batch size of 3
  88. $executor->writeResults($results);
  89. ?>

Add your comment