[Tutor] Lock File Usage
ad^2
adsquaired at gmail.com
Wed Feb 1 11:22:44 EST 2017
On Mon, Jan 30, 2017 at 7:33 PM, Ben Finney <ben+python at benfinney.id.au>
wrote:
> "ad^2" <adsquaired at gmail.com> writes:
>
> > So, IF: no lock file, create a lock file, execute, delete lock file
> > when finished successfully. ElSE: the script is running, exit. Then,
> > cron will try again an hour later.
> >
> > I do not necessarily require a "lock file" just looking for a
> > recommendation on a best practice with low complexity to make this
> > work.
>
> The third-party ‘fasteners’ library provides an API for locks
> <URL:https://pypi.python.org/pypi/fasteners> that you will want to
> consider.
>
> Specifically, the interpprocess lock decorators
> <URL:https://fasteners.readthedocs.io/en/latest/
> examples.html#lock-decorator>
> seem to be what you want.
> -------------------
>
Thanks for the help guys. This is what I ended up going with that works.
Requires: lockfile, syslog and os modules
pid = ('/var/lock/' + os.path.splitext(os.path.basename(__file__))[0])
try:
lock = filelock.FileLock(pid)
lock.acquire(timeout = 1)
# my code function 1
# my code function 2
# and so on....
lock.release(force = True)
os.unlink(pid)
except (IOError, OSError) as e:
syslog.syslog('%s' % e)
print e
More information about the Tutor
mailing list