Ping CronMissed from PHP

On this page

PHP's curl extension sends a ping in a few lines. This helper reports the start, the success or the failure with the end of the exception text, sets a timeout, and ignores its own errors so the job's exit status stays the job's own.

What should a PHP job send?

  • A request to /start before the work, so CronMissed can time the run and notice a job that never finishes.
  • A request to the plain URL when the work succeeded, or to /fail when it did not. /<exit status> works too: 0 is a success and any other number is a failure.
  • The end of the output in the request body, up to 100,000 bytes, so the alert shows the error without a trip to the server.

What is the helper?

cronmissed.php
<?php
function cronmissed_ping(string $url, string $suffix = '', ?string $body = null): void
{
    $curl = curl_init($url . $suffix);
    curl_setopt_array($curl, [CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 10]);
    if ($body !== null) {
        curl_setopt($curl, CURLOPT_POST, true);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $body);
    }
    curl_exec($curl); // a lost ping must never break the job
    curl_close($curl);
}

function cronmissed_run(string $url, callable $job): void
{
    cronmissed_ping($url, '/start');
    try {
        $job();
    } catch (Throwable $e) {
        cronmissed_ping($url, '/fail', substr((string) $e, -100000));
        throw $e;
    }
    cronmissed_ping($url);
}

cronmissed_run(getenv('CRONMISSED_PING_URL'), function () {
    // the work
});

Keep the ping URL in an environment variable or a secret store, never in a public repository: the URL is the check's only credential.

Is there a shortcut for Laravel?

Yes. The scheduler has pingBefore, pingOnSuccess and pingOnFailure methods, covered in the Laravel scheduler guide.

Questions and answers

What if the curl extension is not installed?
Use file_get_contents with a stream context that sets a timeout and the POST method, or install the extension. Most PHP builds include curl.
Does a PHP warning count as a failure?
Only if it ends the script with a non-zero status or throws. Convert warnings to exceptions with set_error_handler if you want them to count.
Create the check these snippets report to

Make a check, copy its ping URL into the snippet, and run the job once.

Start monitoring