<?php
/**
* Collects metrics for short-lived tasks.
*
* This script gathers data about task execution, including duration,
* success/failure, and resource usage. Designed for short-lived operations.
*/
class TaskMetricsCollector {
private $taskName; // Name of the task being measured
private $startTime; // Timestamp of task start
private $endTime; // Timestamp of task end
private $success; // Boolean indicating task success
private $duration; // Task execution time in seconds
private $resourcesUsed; // An array of resource usage metrics
/**
* Constructor
* @param string $taskName The name of the task.
*/
public function __construct(string $taskName) {
$this->taskName = $taskName;
$this->startTime = time(); // Record the start time
$this->endTime = null; // Initialize end time
$this->success = false; // Initialize success
$this->duration = 0; // Initialize duration
$this->resourcesUsed = []; // Initialize resource usage
}
/**
* Start the task. Called at the beginning of the task.
*/
public function start() {
//Do nothing, just setup the start time
}
/**
* End the task and record metrics.
* @param bool $success Whether the task completed successfully.
*/
public function end(bool $success): void {
$this->endTime = time(); // Record the end time
$this->success = $success; // Record success status
$this->duration = round((time() - $this->startTime) / 60); // Calculate duration in minutes
$this->resourcesUsed = $this->getResourceUsage(); //Get Resource Usage
// Output the collected metrics (replace with your desired storage method)
$this->outputMetrics();
}
/**
* Get resource usage metrics. This is a placeholder; implement your
* resource monitoring logic here.
* @return array
*/
private function getResourceUsage(): array {
// Example: Simulate resource usage
$cpuUsage = rand(1, 100);
$memoryUsage = rand(10, 500);
$networkBytes = rand(1000, 10000);
return [
'cpu' => $cpuUsage,
'memory' => $memoryUsage,
'network' => $networkBytes
];
}
/**
* Output the collected metrics. Replace with your preferred output method
* (e.g., logging, database insertion, sending to a monitoring service).
*/
private function outputMetrics(): void {
echo "Task: " . $this->taskName . "\n";
echo "Start Time: " . date("Y-m-d H:i:s", $this->startTime) . "\n";
echo "End Time: " . date("Y-m-d H:i:s", $this->endTime) . "\n";
echo "Success: " . ($this->success ? 'true' : 'false') . "\n";
echo "Duration: " . $this->duration . " minutes\n";
echo "Resources Used: " . json_encode($this->resourcesUsed, JSON_PRETTY_PRINT) . "\n";
echo "--------------------\n";
}
}
// Example Usage:
// Create a collector for a specific task
$taskCollector = new TaskMetricsCollector('short_task');
// Start the task
$taskCollector->start();
// Simulate task execution (replace with your actual task code)
sleep(5); // Simulate 5 seconds of work
// End the task
$taskCollector->end(true); // Indicate successful completion
?>
Add your comment