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.
    // ...

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')) {

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.


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

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


The Drupal 8 version would be:

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


| 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.