How to use a timer in Python?

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


Nico Grubert <nicogrubert at gmail.com> wrote:
>  There is no cronjob anymore now. I just need to check if there is a lock 
>  file. How would you modify my short program to avoid the situation "Ie 
>  someone can get in there after you read the directory but before
>  you create the file."?

You can't do it with files.

You can do it with directories though...

Both processes need to be using the same lock, so something like this
(all untested ;-)

import os
import time
WINDOWS_SHARE = 'C:\\Temp'
lock_file = os.path.join(WINDOWS_SHARE, "transfer.lock")

gained_lock = False
while not gained_lock:
    try:
        os.mkdir(lock_file)
	gained_lock = True
    except OSError:
        print "Busy, please wait..."
        time.sleep(10)

f = open(WINDOWS_SHARE + '/myfile', 'w')
f.write("test 123")
f.close()

os.rmdir(lock_file)

print "Done!"

You need to do the same thing to the program which currently creates
transfer.lock - so it waits if the transfer.lock is in existence too.

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



More information about the Python-list mailing list