base.py 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137
  1. from abc import ABCMeta, abstractmethod
  2. from collections import defaultdict
  3. from datetime import datetime, timedelta
  4. from traceback import format_tb
  5. import logging
  6. import sys
  7. from pytz import utc
  8. import six
  9. from apscheduler.events import (
  10. JobExecutionEvent, EVENT_JOB_MISSED, EVENT_JOB_ERROR, EVENT_JOB_EXECUTED)
  11. class MaxInstancesReachedError(Exception):
  12. def __init__(self, job):
  13. super(MaxInstancesReachedError, self).__init__(
  14. 'Job "%s" has already reached its maximum number of instances (%d)' %
  15. (job.id, job.max_instances))
  16. class BaseExecutor(six.with_metaclass(ABCMeta, object)):
  17. """Abstract base class that defines the interface that every executor must implement."""
  18. _scheduler = None
  19. _lock = None
  20. _logger = logging.getLogger('apscheduler.executors')
  21. def __init__(self):
  22. super(BaseExecutor, self).__init__()
  23. self._instances = defaultdict(lambda: 0)
  24. def start(self, scheduler, alias):
  25. """
  26. Called by the scheduler when the scheduler is being started or when the executor is being
  27. added to an already running scheduler.
  28. :param apscheduler.schedulers.base.BaseScheduler scheduler: the scheduler that is starting
  29. this executor
  30. :param str|unicode alias: alias of this executor as it was assigned to the scheduler
  31. """
  32. self._scheduler = scheduler
  33. self._lock = scheduler._create_lock()
  34. self._logger = logging.getLogger('apscheduler.executors.%s' % alias)
  35. def shutdown(self, wait=True):
  36. """
  37. Shuts down this executor.
  38. :param bool wait: ``True`` to wait until all submitted jobs
  39. have been executed
  40. """
  41. def submit_job(self, job, run_times):
  42. """
  43. Submits job for execution.
  44. :param Job job: job to execute
  45. :param list[datetime] run_times: list of datetimes specifying
  46. when the job should have been run
  47. :raises MaxInstancesReachedError: if the maximum number of
  48. allowed instances for this job has been reached
  49. """
  50. assert self._lock is not None, 'This executor has not been started yet'
  51. with self._lock:
  52. if self._instances[job.id] >= job.max_instances:
  53. raise MaxInstancesReachedError(job)
  54. self._do_submit_job(job, run_times)
  55. self._instances[job.id] += 1
  56. @abstractmethod
  57. def _do_submit_job(self, job, run_times):
  58. """Performs the actual task of scheduling `run_job` to be called."""
  59. def _run_job_success(self, job_id, events):
  60. """
  61. Called by the executor with the list of generated events when :func:`run_job` has been
  62. successfully called.
  63. """
  64. with self._lock:
  65. self._instances[job_id] -= 1
  66. if self._instances[job_id] == 0:
  67. del self._instances[job_id]
  68. for event in events:
  69. self._scheduler._dispatch_event(event)
  70. def _run_job_error(self, job_id, exc, traceback=None):
  71. """Called by the executor with the exception if there is an error calling `run_job`."""
  72. with self._lock:
  73. self._instances[job_id] -= 1
  74. if self._instances[job_id] == 0:
  75. del self._instances[job_id]
  76. exc_info = (exc.__class__, exc, traceback)
  77. self._logger.error('Error running job %s', job_id, exc_info=exc_info)
  78. def run_job(job, jobstore_alias, run_times, logger_name):
  79. """
  80. Called by executors to run the job. Returns a list of scheduler events to be dispatched by the
  81. scheduler.
  82. """
  83. events = []
  84. logger = logging.getLogger(logger_name)
  85. for run_time in run_times:
  86. # See if the job missed its run time window, and handle
  87. # possible misfires accordingly
  88. if job.misfire_grace_time is not None:
  89. difference = datetime.now(utc) - run_time
  90. grace_time = timedelta(seconds=job.misfire_grace_time)
  91. if difference > grace_time:
  92. events.append(JobExecutionEvent(EVENT_JOB_MISSED, job.id, jobstore_alias,
  93. run_time))
  94. logger.warning('Run time of job "%s" was missed by %s', job, difference)
  95. continue
  96. logger.info('Running job "%s" (scheduled at %s)', job, run_time)
  97. try:
  98. retval = job.func(*job.args, **job.kwargs)
  99. except:
  100. exc, tb = sys.exc_info()[1:]
  101. formatted_tb = ''.join(format_tb(tb))
  102. events.append(JobExecutionEvent(EVENT_JOB_ERROR, job.id, jobstore_alias, run_time,
  103. exception=exc, traceback=formatted_tb))
  104. logger.exception('Job "%s" raised an exception', job)
  105. else:
  106. events.append(JobExecutionEvent(EVENT_JOB_EXECUTED, job.id, jobstore_alias, run_time,
  107. retval=retval))
  108. logger.info('Job "%s" executed successfully', job)
  109. return events