base_py3.py 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. import logging
  2. import sys
  3. import traceback
  4. from datetime import datetime, timedelta
  5. from traceback import format_tb
  6. from pytz import utc
  7. from apscheduler.events import (
  8. JobExecutionEvent, EVENT_JOB_MISSED, EVENT_JOB_ERROR, EVENT_JOB_EXECUTED)
  9. async def run_coroutine_job(job, jobstore_alias, run_times, logger_name):
  10. """Coroutine version of run_job()."""
  11. events = []
  12. logger = logging.getLogger(logger_name)
  13. for run_time in run_times:
  14. # See if the job missed its run time window, and handle possible misfires accordingly
  15. if job.misfire_grace_time is not None:
  16. difference = datetime.now(utc) - run_time
  17. grace_time = timedelta(seconds=job.misfire_grace_time)
  18. if difference > grace_time:
  19. events.append(JobExecutionEvent(EVENT_JOB_MISSED, job.id, jobstore_alias,
  20. run_time))
  21. logger.warning('Run time of job "%s" was missed by %s', job, difference)
  22. continue
  23. logger.info('Running job "%s" (scheduled at %s)', job, run_time)
  24. try:
  25. retval = await job.func(*job.args, **job.kwargs)
  26. except BaseException:
  27. exc, tb = sys.exc_info()[1:]
  28. formatted_tb = ''.join(format_tb(tb))
  29. events.append(JobExecutionEvent(EVENT_JOB_ERROR, job.id, jobstore_alias, run_time,
  30. exception=exc, traceback=formatted_tb))
  31. logger.exception('Job "%s" raised an exception', job)
  32. traceback.clear_frames(tb)
  33. else:
  34. events.append(JobExecutionEvent(EVENT_JOB_EXECUTED, job.id, jobstore_alias, run_time,
  35. retval=retval))
  36. logger.info('Job "%s" executed successfully', job)
  37. return events