Build a PHP Guzzle Monitoring Helper for Cron Jobs
PHPThe Problem
Adding monitoring to every PHP cron script individually leads to inconsistency and duplicated code.
The Solution
Build a reusable PHP class using Guzzle that wraps your job logic with automatic start/success/fail pings.
Reusable Pattern
Create a CronMonitor class that accepts a ping URL and a callable. It handles start, success, and fail pings automatically with proper error handling.
Code Examples
Reusable CronMonitor class
PHP<?php
use GuzzleHttp\Client;
class CronMonitor {
private Client $client;
private string $pingUrl;
public function __construct(string $pingUrl) {
$this->pingUrl = $pingUrl;
$this->client = new Client(['timeout' => 10]);
}
public function run(callable $job): mixed {
$this->ping('/start');
try {
$result = $job();
$this->ping('');
return $result;
} catch (\Throwable $e) {
$this->ping('/fail');
throw $e;
}
}
private function ping(string $suffix): void {
try { $this->client->get($this->pingUrl . $suffix); }
catch (\Throwable $e) {} // Don't let monitoring break the job
}
}
// Usage
$monitor = new CronMonitor('https://ping.cronrabbit.com/your-id');
$monitor->run(fn() => processNightlyBatch());