periodic.py 764 B

123456789101112131415161718192021222324252627282930313233
  1. import atexit
  2. import os
  3. import threading
  4. lockfiles = []
  5. def init_task(fn, period, lockfile='/opt/stackbrew/brw.lock', logger=None):
  6. def periodic(logger):
  7. if logger is not None:
  8. logger.info('Periodic task started')
  9. t = threading.Timer(period, periodic, [logger])
  10. t.daemon = True
  11. t.start()
  12. fn()
  13. if os.path.exists(lockfile):
  14. raise RuntimeError('Lockfile already present.')
  15. open(lockfile, 'w').close()
  16. lockfiles.append(lockfile)
  17. t = threading.Timer(0, periodic, [logger])
  18. t.daemon = True
  19. t.start()
  20. def clear_lockfiles(lockfiles):
  21. for lock in lockfiles:
  22. os.remove(lock)
  23. def on_exit(lockfiles):
  24. clear_lockfiles(lockfiles)
  25. atexit.register(on_exit, lockfiles)