How to use a timer in Python?

Nick Craig-Wood nick at craig-wood.com
Fri Sep 23 04:30:01 EDT 2005


Nico Grubert <nicogrubert at gmail.com> wrote:
>  on a Linux machine running Python 2.3.5. I want to create a file 
>  'newfile' in a directory '/tmp' only if there is no file 'transfer.lock' 
>  in '/temp'.
>  A cronjob creates a file 'transfer.lock' in '/temp' directory every 15 
>  minutes while the cronjob is doing something. This job takes around 30 
>  seconds. During these 30 seconds the 'transfer.lock' file is present in 
>  the '/temp' directory and I must not create 'newfile'. After the cronjob 
>  has been finished, the 'transfer.lock' file is deleted from '/temp' and 
>  I can create 'newfile'.

That all sounds very race-y to me!  The cron-job and the other process
need to take the same lock, otherwise the cron-job will start 1ms
after the other process checks for transfer.lock and before it has a
chance to create newfile and there will be trouble.

Using files as locks isn't brilliant because the operations "read to
see if the lock is there" and "create the file isn't" aren't atomic.
Ie someone can get in there after you read the directory but before
you create the file.

However creating a directory is atomic, so you can take the lock by
os.mkdir("/tmp/lock").  If that succeeded you got the lock, if it
failed (threw OSError) then you didn't.  If it failed then just
time.sleep(1) and try again.  This kind of locking works cross
platform too.  You can use it in shell too, eg "mkdir /tmp/lock ||
exit 1" in your cronjob.

You could wrap the locking up into a module of course, and I bet
someone already did.

-- 
Nick Craig-Wood <nick at craig-wood.com> -- http://www.craig-wood.com/nick



More information about the Python-list mailing list