0

I understand how locks work, thanks to this post. Very straightforward:

function mymodule_long_operation() {
  if (lock_acquire('mymodule_long_operation')) {
    // Do the long operation here.
    // ...
    lock_release('mymodule_long_operation');
  }
}

My problem is that my function can get "stuck" if lock_release is never hit. So how can I get my function to work again if something goes wrong here:

function mymodule_long_operation() {
  if (lock_acquire('mymodule_long_operation')) {
    // SOMETHING GOES WRONG HERE!
    lock_release('mymodule_long_operation');
  }
}

Yes, I can put the whole function around a try/catch and release the lock in the catch. But as a developer, I often add "die()" in my code when working. So I can easily trigger this function into an unexecutable state.

Is there some way to make the lock expire after a while? Or to make the lock expire as part of some gauranteed garbage collection function?

Any ideas would be highly appreciated! Thanks!

** UPDATE **

Nevermind me adding die() in my code. What if the function times out? Then it wont reach the release. I'm sure there are more cases to validate this as a problem.

1

Is there some way to make the lock expire after a while?

lock_acquire takes a second parameter, defining the lifetime of the lock:

https://api.drupal.org/api/drupal/includes%21lock.inc/function/lock_acquire/7.x

The Drupal 8 version would be:

lock->acquire($name, $timeout);

https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Lock%21DatabaseLockBackend.php/function/DatabaseLockBackend%3A%3Aacquire/8.2.x

| improve this answer | |
  • Rad! But any idea where that parameter lives in Drupal 8? – coderama Jun 24 '19 at 20:25
  • Nevermind, found it. it's lock->acquire($name, $timeout)! – coderama Jun 24 '19 at 20:26
  • Sorry. Thought this question was for Drupal 7. – Kevin Jun 24 '19 at 20:39
  • 1
    @Kevin You can update the answer for the Drupal 8 part. – kiamlaluno Jun 25 '19 at 6:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.