How to lock django commands so it will not run twise in the same time?
+2
A:
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.
cji
2010-08-11 15:02:25
Something wrong! It have to be try statement? or maybe we need to check if is_locked=true ????
Pol
2010-08-11 15:47:40
@Pol You're right, I corrected example.
cji
2010-08-11 16:46:14
+1
A:
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
f4nt
2010-08-11 15:16:47