<?php
/**
* Timestamp Script Executor - Optimized for Batch Processing & Low Memory
*/
class TimestampExecutor
{
private $script_paths = [];
private $output_dir = '';
public function __construct(array $script_paths, string $output_dir = '')
{
$this->script_paths = $script_paths;
$this->output_dir = rtrim($output_dir, '/'); // Ensure no trailing slash
}
/**
* Executes timestamp scripts in batches.
*
* @param int $batch_size The number of scripts to execute in each batch.
* @return array An array of execution results (success/failure).
*/
public function executeScripts(int $batch_size = 5)
{
$results = [];
$script_count = count($this->script_paths);
if ($script_count === 0) {
return $results; // Return empty array if no scripts
}
for ($i = 0; $i < $script_count; $i += $batch_size) {
$batch = array_slice($this->script_paths, $i, $batch_size);
$batch_results = [];
foreach ($batch as $script_path) {
$result = $this->executeScript($script_path);
$batch_results[] = $result;
}
$results = array_merge($results, $batch_results);
}
return $results;
}
/**
* Executes a single timestamp script.
*
* @param string $script_path The path to the timestamp script.
* @return string 'success' or 'failure'
*/
private function executeScript(string $script_path): string
{
$command = "php " . escapeshellarg($script_path); //Sanitize the script path
$output = [];
$return_var = 0;
exec($command, $output, $return_var);
if ($return_var === 0) {
return 'success';
} else {
return 'failure';
}
}
/**
* Writes output to files based on script results.
*
* @param array $results Array of execution results (success/failure).
*/
public function writeResults(array $results): void
{
if (empty($results)) {
return;
}
$log_file = $this->output_dir . '/timestamp_execution.log';
file_put_contents($log_file, date('Y-m-d H:i:s') . " - Timestamp Execution Log\n");
foreach ($results as $result) {
file_put_contents($log_file, date('Y-m-d H:i:s') . " - " . $result . "\n", FILE_APPEND);
}
}
}
// Example Usage:
$scripts = [
'script1.php',
'script2.php',
'script3.php',
'script4.php',
'script5.php',
'script6.php',
'script7.php',
'script8.php',
'script9.php',
'script10.php',
];
$executor = new TimestampExecutor($scripts, '/path/to/output');
$results = $executor->executeScripts(3); // Batch size of 3
$executor->writeResults($results);
?>
Add your comment