run.py 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. """
  4. Script that runs a directory backup job periodically according
  5. to the interval defined by the INTERVAL_NAME environment variable.
  6. """
  7. import time
  8. import datetime
  9. import subprocess
  10. import functools
  11. import traceback
  12. import os
  13. import schedule
  14. BACKUP_SCRIPT_PATH = "/app/backup.sh"
  15. ENV_BACKUP_INTERVAL = "BACKUP_INTERVAL"
  16. ENV_BACKUP_TIME = "BACKUP_TIME"
  17. TIME_FORMAT = "%H:%M"
  18. def catch_exceptions(job_func):
  19. @functools.wraps(job_func)
  20. def wrapper(*args, **kwargs):
  21. try:
  22. job_func(*args, **kwargs)
  23. except:
  24. print(traceback.format_exc())
  25. return wrapper
  26. @catch_exceptions
  27. def backup_job():
  28. print("Executing backup at {}".format(datetime.datetime.now().isoformat()))
  29. backup_result = subprocess.check_output([BACKUP_SCRIPT_PATH])
  30. print(backup_result)
  31. print("Backup finished at {}".format(datetime.datetime.now().isoformat()))
  32. if __name__ == "__main__":
  33. print("Starting periodic directory backup at {}".format(datetime.datetime.now().isoformat()))
  34. try:
  35. interval_days = int(os.environ.get(ENV_BACKUP_INTERVAL))
  36. except:
  37. raise ValueError("Undefined or invalid var: {}".format(ENV_BACKUP_INTERVAL))
  38. try:
  39. backup_time = os.environ.get(ENV_BACKUP_TIME)
  40. datetime.datetime.strptime(backup_time, TIME_FORMAT)
  41. except:
  42. raise ValueError("Undefined or invalid var: {}".format(ENV_BACKUP_TIME))
  43. print("Executing backups every {} day/s at {}".format(interval_days, backup_time))
  44. schedule.every(interval_days).days.at(backup_time).do(backup_job)
  45. while True:
  46. schedule.run_pending()
  47. time.sleep(1)