How to lock django commands so it will not run twise in the same time?

up vote 2 down vote accepted

Create a lock somewhere - I recently saw very simple lock implementation that used cache:

LOCK_EXPIRE = 60 * 5

lock_id = "%s-lock-%s" % (self.name, id_hexdigest) #computed earlier

is_locked = lambda: str(cache.get(lock_id)) == "true"
acquire_lock = lambda: cache.set(lock_id, "true", LOCK_EXPIRE)
release_lock = lambda: cache.set(lock_id, "nil", 1)

if not is_locked():
    aquire_lock()
    try:
        #do something
    finally:
        release_lock()

It's just one of many possible implementations.

Edit: Corrected, I just pasted code without thinking. try...finally block is used to ensure that lock is always released, no matter what happens - but of course if statement is also necessary.

  • Something wrong! It have to be try statement? or maybe we need to check if is_locked=true ???? – Pol Aug 11 '10 at 15:47
  • @Pol You're right, I corrected example. – cji Aug 11 '10 at 16:46

There are a bunch of different ways to do this. cji's method looks like it'd work just fine. One thing I tend to do is if my background jobs are operating on model objects, I use status fields to determine if the job can run.

class BookModel(models.Model):
    status_choices = ((1, 'new'), ('2', 'processed'))
    name = models.CharField(max_length=12)
    status = models.CharField(max_length=12, choices=status_choices)

Then if I'm performing something on those books I can do something like so:

if book.status is 1:
    ## do something

Your Answer

 

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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