peppeocchi / php-cron-scheduler

PHP cron job scheduler
MIT License
808 stars 143 forks source link

Remove lock file of failed only-one callable job #142

Open dmitry027 opened 1 year ago

dmitry027 commented 1 year ago

Hi,

I am trying to find out what should I do in case only-one callable job is failed:

$scheduler = new Scheduler();

$scheduler->call(function () {
    // ...
    throw new \Exception();
    // ...
}, [], 'job-id')->onlyOne();

$scheduler->run();

In this case lock file remains untouched and the job will not be executed again until I delete the lock file manually. I would like to change this behavior and let the job run again even if previous execution has failed. To do this I need to know the location of the lock file, but the Job class doesn't seem to provide that capability.

I ended up with the following hack:

foreach ($scheduler->getFailedJobs() as $failedJob) {
    unlink('/tmp/' . $failedJob->getJob()->getId() . '.lock');
}

Do you think it makes sense to allow the client code to access lock file path or maybe call removeLockFile() from the outside?

peppeocchi commented 1 year ago

Hi @dmitry027 what you say makes sense, maybe I could add a new method to chain on the schedule, something like

$scheduler->call(function () {
    // ...
    throw new \Exception();
    // ...
}, [], 'job-id')->onlyOne()->removeLockOnFailure();
lenmarknate commented 10 months ago

Yes, although it is not intuitive to me that the default would be to keep the job locked if it failed. I would expect the default behavior to be to try again, not to require explicit removal of the lock file on failure.

stevevance commented 10 months ago

I added this raw command my cron scheduler to remove old lock files (the command that the lock file is attached to usually takes 10 minutes to complete, so two hours is a generous amount of time to let the command finish).

$scheduler->raw('find ../cache -mmin +119 -type f -name "*.lock" -delete')->hourly()->then(function ($output) use ($logger) {
        $logger->info("Removed .lock files older than 2 hours");
    });