Home  >  Q&A  >  body text

Laravel cache lock already locked?

TLDR: How to check if a Laravel atomic lock is locked without locking it and checking the return value of the $lock->get() call?

I have multiple Laravel commands executed through the scheduler. A command is not scheduled and if it is running, no other commands should be run. So I introduced atomic cache lock from Laravel like this:

private function checkSetupRunning(){
    $lock = Cache::store('locks')->getStore()->lock(
        self::RUNNING_KEY, // name for the lock
        owner: self::class
    );

    if ($lock->get(fn() => null) === false) {
        throw new SetupRunningException();
    }
}

This does work as expected, however, when running multiple of these commands in parallel, sometimes it seems that the lock has been acquired via the checkSetupRunning function of another command and therefore fails, even though the setup-command is not running.

So I need a way to check if the lock has been acquired without locking the lock. I checked the documentation and some code but couldn't find a solution.

P粉818561682P粉818561682229 days ago485

reply all(1)I'll reply

  • P粉604507867

    P粉6045078672024-03-28 12:32:45

    This is how we found it

     public static function getCacheLockOwner(string $key): string|false
     {
            return Cache::lockConnection()->client()->get(Cache::getPrefix().$key);
     }
    

    It returns the lock owner (a string) if present, otherwise it returns false.

    reply
    0
  • Cancelreply