kerekit/lockfile

Lockfile mechanism with timeout option

v2.0.0 2025-04-16 11:14 UTC

This package is auto-updated.

Last update: 2025-04-16 11:14:42 UTC


README

Install

composer install kerekit/lockfile

Example

<?php
use Kerekit\Lockfile\{Exception,Lock};

// Set a lockfile with 4 hours of timeout
$lock = new Lock (__DIR__ . '/lockfile.json', 4 * 60 * 60);

// Pass a callable to Lock::run()
try {
    $lock->run (function () {
        /**
         * Do something here...
         * - If it completes successfully, lockfile is closed, with last
         *   completion time updated.
         * - If an exception is thrown, lockfile is closed, but last completion
         *   time remains the same.
         * - If lockfile's last completion time is too old, fail with an
         *   exception.
         */
    });
}

// Catch lockfile timeout
catch (Exception $e) {
    if ($e->getCode () === Exception::CODE_TIMEOUT) {
        echo "ERROR: Lockfile timeout reached!\n";
        exit (1);
    } else {
        echo "ERROR: Failed to handle lockfile (" . $e->getMessage () . ")\n";
        exit (1);
    }
}

// Ignore any other errors
catch (\Throwable $e) {}