base.py 43 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037
  1. from __future__ import print_function
  2. from abc import ABCMeta, abstractmethod
  3. from threading import RLock
  4. from datetime import datetime, timedelta
  5. from logging import getLogger
  6. import warnings
  7. import sys
  8. from tzlocal import get_localzone
  9. import six
  10. from apscheduler.schedulers import SchedulerAlreadyRunningError, SchedulerNotRunningError
  11. from apscheduler.executors.base import MaxInstancesReachedError, BaseExecutor
  12. from apscheduler.executors.pool import ThreadPoolExecutor
  13. from apscheduler.jobstores.base import ConflictingIdError, JobLookupError, BaseJobStore
  14. from apscheduler.jobstores.memory import MemoryJobStore
  15. from apscheduler.job import Job
  16. from apscheduler.triggers.base import BaseTrigger
  17. from apscheduler.util import (
  18. asbool, asint, astimezone, maybe_ref, timedelta_seconds, undefined, TIMEOUT_MAX)
  19. from apscheduler.events import (
  20. SchedulerEvent, JobEvent, JobSubmissionEvent, EVENT_SCHEDULER_START, EVENT_SCHEDULER_SHUTDOWN,
  21. EVENT_JOBSTORE_ADDED, EVENT_JOBSTORE_REMOVED, EVENT_ALL, EVENT_JOB_MODIFIED, EVENT_JOB_REMOVED,
  22. EVENT_JOB_ADDED, EVENT_EXECUTOR_ADDED, EVENT_EXECUTOR_REMOVED, EVENT_ALL_JOBS_REMOVED,
  23. EVENT_JOB_SUBMITTED, EVENT_JOB_MAX_INSTANCES, EVENT_SCHEDULER_RESUMED, EVENT_SCHEDULER_PAUSED)
  24. try:
  25. from collections.abc import MutableMapping
  26. except ImportError:
  27. from collections import MutableMapping
  28. try:
  29. from importlib.metadata import entry_points
  30. except ModuleNotFoundError:
  31. from importlib_metadata import entry_points
  32. #: constant indicating a scheduler's stopped state
  33. STATE_STOPPED = 0
  34. #: constant indicating a scheduler's running state (started and processing jobs)
  35. STATE_RUNNING = 1
  36. #: constant indicating a scheduler's paused state (started but not processing jobs)
  37. STATE_PAUSED = 2
  38. class BaseScheduler(six.with_metaclass(ABCMeta)):
  39. """
  40. Abstract base class for all schedulers.
  41. Takes the following keyword arguments:
  42. :param str|logging.Logger logger: logger to use for the scheduler's logging (defaults to
  43. apscheduler.scheduler)
  44. :param str|datetime.tzinfo timezone: the default time zone (defaults to the local timezone)
  45. :param int|float jobstore_retry_interval: the minimum number of seconds to wait between
  46. retries in the scheduler's main loop if the job store raises an exception when getting
  47. the list of due jobs
  48. :param dict job_defaults: default values for newly added jobs
  49. :param dict jobstores: a dictionary of job store alias -> job store instance or configuration
  50. dict
  51. :param dict executors: a dictionary of executor alias -> executor instance or configuration
  52. dict
  53. :ivar int state: current running state of the scheduler (one of the following constants from
  54. ``apscheduler.schedulers.base``: ``STATE_STOPPED``, ``STATE_RUNNING``, ``STATE_PAUSED``)
  55. .. seealso:: :ref:`scheduler-config`
  56. """
  57. # The `group=...` API is only available in the backport, used in <=3.7, and in std>=3.10.
  58. if (3, 8) <= sys.version_info < (3, 10):
  59. _trigger_plugins = {ep.name: ep for ep in entry_points()['apscheduler.triggers']}
  60. _executor_plugins = {ep.name: ep for ep in entry_points()['apscheduler.executors']}
  61. _jobstore_plugins = {ep.name: ep for ep in entry_points()['apscheduler.jobstores']}
  62. else:
  63. _trigger_plugins = {ep.name: ep for ep in entry_points(group='apscheduler.triggers')}
  64. _executor_plugins = {ep.name: ep for ep in entry_points(group='apscheduler.executors')}
  65. _jobstore_plugins = {ep.name: ep for ep in entry_points(group='apscheduler.jobstores')}
  66. _trigger_classes = {}
  67. _executor_classes = {}
  68. _jobstore_classes = {}
  69. #
  70. # Public API
  71. #
  72. def __init__(self, gconfig={}, **options):
  73. super(BaseScheduler, self).__init__()
  74. self._executors = {}
  75. self._executors_lock = self._create_lock()
  76. self._jobstores = {}
  77. self._jobstores_lock = self._create_lock()
  78. self._listeners = []
  79. self._listeners_lock = self._create_lock()
  80. self._pending_jobs = []
  81. self.state = STATE_STOPPED
  82. self.configure(gconfig, **options)
  83. def __getstate__(self):
  84. raise TypeError("Schedulers cannot be serialized. Ensure that you are not passing a "
  85. "scheduler instance as an argument to a job, or scheduling an instance "
  86. "method where the instance contains a scheduler as an attribute.")
  87. def configure(self, gconfig={}, prefix='apscheduler.', **options):
  88. """
  89. Reconfigures the scheduler with the given options.
  90. Can only be done when the scheduler isn't running.
  91. :param dict gconfig: a "global" configuration dictionary whose values can be overridden by
  92. keyword arguments to this method
  93. :param str|unicode prefix: pick only those keys from ``gconfig`` that are prefixed with
  94. this string (pass an empty string or ``None`` to use all keys)
  95. :raises SchedulerAlreadyRunningError: if the scheduler is already running
  96. """
  97. if self.state != STATE_STOPPED:
  98. raise SchedulerAlreadyRunningError
  99. # If a non-empty prefix was given, strip it from the keys in the
  100. # global configuration dict
  101. if prefix:
  102. prefixlen = len(prefix)
  103. gconfig = dict((key[prefixlen:], value) for key, value in six.iteritems(gconfig)
  104. if key.startswith(prefix))
  105. # Create a structure from the dotted options
  106. # (e.g. "a.b.c = d" -> {'a': {'b': {'c': 'd'}}})
  107. config = {}
  108. for key, value in six.iteritems(gconfig):
  109. parts = key.split('.')
  110. parent = config
  111. key = parts.pop(0)
  112. while parts:
  113. parent = parent.setdefault(key, {})
  114. key = parts.pop(0)
  115. parent[key] = value
  116. # Override any options with explicit keyword arguments
  117. config.update(options)
  118. self._configure(config)
  119. def start(self, paused=False):
  120. """
  121. Start the configured executors and job stores and begin processing scheduled jobs.
  122. :param bool paused: if ``True``, don't start job processing until :meth:`resume` is called
  123. :raises SchedulerAlreadyRunningError: if the scheduler is already running
  124. :raises RuntimeError: if running under uWSGI with threads disabled
  125. """
  126. if self.state != STATE_STOPPED:
  127. raise SchedulerAlreadyRunningError
  128. self._check_uwsgi()
  129. with self._executors_lock:
  130. # Create a default executor if nothing else is configured
  131. if 'default' not in self._executors:
  132. self.add_executor(self._create_default_executor(), 'default')
  133. # Start all the executors
  134. for alias, executor in six.iteritems(self._executors):
  135. executor.start(self, alias)
  136. with self._jobstores_lock:
  137. # Create a default job store if nothing else is configured
  138. if 'default' not in self._jobstores:
  139. self.add_jobstore(self._create_default_jobstore(), 'default')
  140. # Start all the job stores
  141. for alias, store in six.iteritems(self._jobstores):
  142. store.start(self, alias)
  143. # Schedule all pending jobs
  144. for job, jobstore_alias, replace_existing in self._pending_jobs:
  145. self._real_add_job(job, jobstore_alias, replace_existing)
  146. del self._pending_jobs[:]
  147. self.state = STATE_PAUSED if paused else STATE_RUNNING
  148. self._logger.info('Scheduler started')
  149. self._dispatch_event(SchedulerEvent(EVENT_SCHEDULER_START))
  150. if not paused:
  151. self.wakeup()
  152. @abstractmethod
  153. def shutdown(self, wait=True):
  154. """
  155. Shuts down the scheduler, along with its executors and job stores.
  156. Does not interrupt any currently running jobs.
  157. :param bool wait: ``True`` to wait until all currently executing jobs have finished
  158. :raises SchedulerNotRunningError: if the scheduler has not been started yet
  159. """
  160. if self.state == STATE_STOPPED:
  161. raise SchedulerNotRunningError
  162. self.state = STATE_STOPPED
  163. # Shut down all executors
  164. with self._executors_lock, self._jobstores_lock:
  165. for executor in six.itervalues(self._executors):
  166. executor.shutdown(wait)
  167. # Shut down all job stores
  168. for jobstore in six.itervalues(self._jobstores):
  169. jobstore.shutdown()
  170. self._logger.info('Scheduler has been shut down')
  171. self._dispatch_event(SchedulerEvent(EVENT_SCHEDULER_SHUTDOWN))
  172. def pause(self):
  173. """
  174. Pause job processing in the scheduler.
  175. This will prevent the scheduler from waking up to do job processing until :meth:`resume`
  176. is called. It will not however stop any already running job processing.
  177. """
  178. if self.state == STATE_STOPPED:
  179. raise SchedulerNotRunningError
  180. elif self.state == STATE_RUNNING:
  181. self.state = STATE_PAUSED
  182. self._logger.info('Paused scheduler job processing')
  183. self._dispatch_event(SchedulerEvent(EVENT_SCHEDULER_PAUSED))
  184. def resume(self):
  185. """Resume job processing in the scheduler."""
  186. if self.state == STATE_STOPPED:
  187. raise SchedulerNotRunningError
  188. elif self.state == STATE_PAUSED:
  189. self.state = STATE_RUNNING
  190. self._logger.info('Resumed scheduler job processing')
  191. self._dispatch_event(SchedulerEvent(EVENT_SCHEDULER_RESUMED))
  192. self.wakeup()
  193. @property
  194. def running(self):
  195. """
  196. Return ``True`` if the scheduler has been started.
  197. This is a shortcut for ``scheduler.state != STATE_STOPPED``.
  198. """
  199. return self.state != STATE_STOPPED
  200. def add_executor(self, executor, alias='default', **executor_opts):
  201. """
  202. Adds an executor to this scheduler.
  203. Any extra keyword arguments will be passed to the executor plugin's constructor, assuming
  204. that the first argument is the name of an executor plugin.
  205. :param str|unicode|apscheduler.executors.base.BaseExecutor executor: either an executor
  206. instance or the name of an executor plugin
  207. :param str|unicode alias: alias for the scheduler
  208. :raises ValueError: if there is already an executor by the given alias
  209. """
  210. with self._executors_lock:
  211. if alias in self._executors:
  212. raise ValueError('This scheduler already has an executor by the alias of "%s"' %
  213. alias)
  214. if isinstance(executor, BaseExecutor):
  215. self._executors[alias] = executor
  216. elif isinstance(executor, six.string_types):
  217. self._executors[alias] = executor = self._create_plugin_instance(
  218. 'executor', executor, executor_opts)
  219. else:
  220. raise TypeError('Expected an executor instance or a string, got %s instead' %
  221. executor.__class__.__name__)
  222. # Start the executor right away if the scheduler is running
  223. if self.state != STATE_STOPPED:
  224. executor.start(self, alias)
  225. self._dispatch_event(SchedulerEvent(EVENT_EXECUTOR_ADDED, alias))
  226. def remove_executor(self, alias, shutdown=True):
  227. """
  228. Removes the executor by the given alias from this scheduler.
  229. :param str|unicode alias: alias of the executor
  230. :param bool shutdown: ``True`` to shut down the executor after
  231. removing it
  232. """
  233. with self._executors_lock:
  234. executor = self._lookup_executor(alias)
  235. del self._executors[alias]
  236. if shutdown:
  237. executor.shutdown()
  238. self._dispatch_event(SchedulerEvent(EVENT_EXECUTOR_REMOVED, alias))
  239. def add_jobstore(self, jobstore, alias='default', **jobstore_opts):
  240. """
  241. Adds a job store to this scheduler.
  242. Any extra keyword arguments will be passed to the job store plugin's constructor, assuming
  243. that the first argument is the name of a job store plugin.
  244. :param str|unicode|apscheduler.jobstores.base.BaseJobStore jobstore: job store to be added
  245. :param str|unicode alias: alias for the job store
  246. :raises ValueError: if there is already a job store by the given alias
  247. """
  248. with self._jobstores_lock:
  249. if alias in self._jobstores:
  250. raise ValueError('This scheduler already has a job store by the alias of "%s"' %
  251. alias)
  252. if isinstance(jobstore, BaseJobStore):
  253. self._jobstores[alias] = jobstore
  254. elif isinstance(jobstore, six.string_types):
  255. self._jobstores[alias] = jobstore = self._create_plugin_instance(
  256. 'jobstore', jobstore, jobstore_opts)
  257. else:
  258. raise TypeError('Expected a job store instance or a string, got %s instead' %
  259. jobstore.__class__.__name__)
  260. # Start the job store right away if the scheduler isn't stopped
  261. if self.state != STATE_STOPPED:
  262. jobstore.start(self, alias)
  263. # Notify listeners that a new job store has been added
  264. self._dispatch_event(SchedulerEvent(EVENT_JOBSTORE_ADDED, alias))
  265. # Notify the scheduler so it can scan the new job store for jobs
  266. if self.state != STATE_STOPPED:
  267. self.wakeup()
  268. def remove_jobstore(self, alias, shutdown=True):
  269. """
  270. Removes the job store by the given alias from this scheduler.
  271. :param str|unicode alias: alias of the job store
  272. :param bool shutdown: ``True`` to shut down the job store after removing it
  273. """
  274. with self._jobstores_lock:
  275. jobstore = self._lookup_jobstore(alias)
  276. del self._jobstores[alias]
  277. if shutdown:
  278. jobstore.shutdown()
  279. self._dispatch_event(SchedulerEvent(EVENT_JOBSTORE_REMOVED, alias))
  280. def add_listener(self, callback, mask=EVENT_ALL):
  281. """
  282. add_listener(callback, mask=EVENT_ALL)
  283. Adds a listener for scheduler events.
  284. When a matching event occurs, ``callback`` is executed with the event object as its
  285. sole argument. If the ``mask`` parameter is not provided, the callback will receive events
  286. of all types.
  287. :param callback: any callable that takes one argument
  288. :param int mask: bitmask that indicates which events should be
  289. listened to
  290. .. seealso:: :mod:`apscheduler.events`
  291. .. seealso:: :ref:`scheduler-events`
  292. """
  293. with self._listeners_lock:
  294. self._listeners.append((callback, mask))
  295. def remove_listener(self, callback):
  296. """Removes a previously added event listener."""
  297. with self._listeners_lock:
  298. for i, (cb, _) in enumerate(self._listeners):
  299. if callback == cb:
  300. del self._listeners[i]
  301. def add_job(self, func, trigger=None, args=None, kwargs=None, id=None, name=None,
  302. misfire_grace_time=undefined, coalesce=undefined, max_instances=undefined,
  303. next_run_time=undefined, jobstore='default', executor='default',
  304. replace_existing=False, **trigger_args):
  305. """
  306. add_job(func, trigger=None, args=None, kwargs=None, id=None, \
  307. name=None, misfire_grace_time=undefined, coalesce=undefined, \
  308. max_instances=undefined, next_run_time=undefined, \
  309. jobstore='default', executor='default', \
  310. replace_existing=False, **trigger_args)
  311. Adds the given job to the job list and wakes up the scheduler if it's already running.
  312. Any option that defaults to ``undefined`` will be replaced with the corresponding default
  313. value when the job is scheduled (which happens when the scheduler is started, or
  314. immediately if the scheduler is already running).
  315. The ``func`` argument can be given either as a callable object or a textual reference in
  316. the ``package.module:some.object`` format, where the first half (separated by ``:``) is an
  317. importable module and the second half is a reference to the callable object, relative to
  318. the module.
  319. The ``trigger`` argument can either be:
  320. #. the alias name of the trigger (e.g. ``date``, ``interval`` or ``cron``), in which case
  321. any extra keyword arguments to this method are passed on to the trigger's constructor
  322. #. an instance of a trigger class
  323. :param func: callable (or a textual reference to one) to run at the given time
  324. :param str|apscheduler.triggers.base.BaseTrigger trigger: trigger that determines when
  325. ``func`` is called
  326. :param list|tuple args: list of positional arguments to call func with
  327. :param dict kwargs: dict of keyword arguments to call func with
  328. :param str|unicode id: explicit identifier for the job (for modifying it later)
  329. :param str|unicode name: textual description of the job
  330. :param int misfire_grace_time: seconds after the designated runtime that the job is still
  331. allowed to be run (or ``None`` to allow the job to run no matter how late it is)
  332. :param bool coalesce: run once instead of many times if the scheduler determines that the
  333. job should be run more than once in succession
  334. :param int max_instances: maximum number of concurrently running instances allowed for this
  335. job
  336. :param datetime next_run_time: when to first run the job, regardless of the trigger (pass
  337. ``None`` to add the job as paused)
  338. :param str|unicode jobstore: alias of the job store to store the job in
  339. :param str|unicode executor: alias of the executor to run the job with
  340. :param bool replace_existing: ``True`` to replace an existing job with the same ``id``
  341. (but retain the number of runs from the existing one)
  342. :rtype: Job
  343. """
  344. job_kwargs = {
  345. 'trigger': self._create_trigger(trigger, trigger_args),
  346. 'executor': executor,
  347. 'func': func,
  348. 'args': tuple(args) if args is not None else (),
  349. 'kwargs': dict(kwargs) if kwargs is not None else {},
  350. 'id': id,
  351. 'name': name,
  352. 'misfire_grace_time': misfire_grace_time,
  353. 'coalesce': coalesce,
  354. 'max_instances': max_instances,
  355. 'next_run_time': next_run_time
  356. }
  357. job_kwargs = dict((key, value) for key, value in six.iteritems(job_kwargs) if
  358. value is not undefined)
  359. job = Job(self, **job_kwargs)
  360. # Don't really add jobs to job stores before the scheduler is up and running
  361. with self._jobstores_lock:
  362. if self.state == STATE_STOPPED:
  363. self._pending_jobs.append((job, jobstore, replace_existing))
  364. self._logger.info('Adding job tentatively -- it will be properly scheduled when '
  365. 'the scheduler starts')
  366. else:
  367. self._real_add_job(job, jobstore, replace_existing)
  368. return job
  369. def scheduled_job(self, trigger, args=None, kwargs=None, id=None, name=None,
  370. misfire_grace_time=undefined, coalesce=undefined, max_instances=undefined,
  371. next_run_time=undefined, jobstore='default', executor='default',
  372. **trigger_args):
  373. """
  374. scheduled_job(trigger, args=None, kwargs=None, id=None, \
  375. name=None, misfire_grace_time=undefined, \
  376. coalesce=undefined, max_instances=undefined, \
  377. next_run_time=undefined, jobstore='default', \
  378. executor='default',**trigger_args)
  379. A decorator version of :meth:`add_job`, except that ``replace_existing`` is always
  380. ``True``.
  381. .. important:: The ``id`` argument must be given if scheduling a job in a persistent job
  382. store. The scheduler cannot, however, enforce this requirement.
  383. """
  384. def inner(func):
  385. self.add_job(func, trigger, args, kwargs, id, name, misfire_grace_time, coalesce,
  386. max_instances, next_run_time, jobstore, executor, True, **trigger_args)
  387. return func
  388. return inner
  389. def modify_job(self, job_id, jobstore=None, **changes):
  390. """
  391. Modifies the properties of a single job.
  392. Modifications are passed to this method as extra keyword arguments.
  393. :param str|unicode job_id: the identifier of the job
  394. :param str|unicode jobstore: alias of the job store that contains the job
  395. :return Job: the relevant job instance
  396. """
  397. with self._jobstores_lock:
  398. job, jobstore = self._lookup_job(job_id, jobstore)
  399. job._modify(**changes)
  400. if jobstore:
  401. self._lookup_jobstore(jobstore).update_job(job)
  402. self._dispatch_event(JobEvent(EVENT_JOB_MODIFIED, job_id, jobstore))
  403. # Wake up the scheduler since the job's next run time may have been changed
  404. if self.state == STATE_RUNNING:
  405. self.wakeup()
  406. return job
  407. def reschedule_job(self, job_id, jobstore=None, trigger=None, **trigger_args):
  408. """
  409. Constructs a new trigger for a job and updates its next run time.
  410. Extra keyword arguments are passed directly to the trigger's constructor.
  411. :param str|unicode job_id: the identifier of the job
  412. :param str|unicode jobstore: alias of the job store that contains the job
  413. :param trigger: alias of the trigger type or a trigger instance
  414. :return Job: the relevant job instance
  415. """
  416. trigger = self._create_trigger(trigger, trigger_args)
  417. now = datetime.now(self.timezone)
  418. next_run_time = trigger.get_next_fire_time(None, now)
  419. return self.modify_job(job_id, jobstore, trigger=trigger, next_run_time=next_run_time)
  420. def pause_job(self, job_id, jobstore=None):
  421. """
  422. Causes the given job not to be executed until it is explicitly resumed.
  423. :param str|unicode job_id: the identifier of the job
  424. :param str|unicode jobstore: alias of the job store that contains the job
  425. :return Job: the relevant job instance
  426. """
  427. return self.modify_job(job_id, jobstore, next_run_time=None)
  428. def resume_job(self, job_id, jobstore=None):
  429. """
  430. Resumes the schedule of the given job, or removes the job if its schedule is finished.
  431. :param str|unicode job_id: the identifier of the job
  432. :param str|unicode jobstore: alias of the job store that contains the job
  433. :return Job|None: the relevant job instance if the job was rescheduled, or ``None`` if no
  434. next run time could be calculated and the job was removed
  435. """
  436. with self._jobstores_lock:
  437. job, jobstore = self._lookup_job(job_id, jobstore)
  438. now = datetime.now(self.timezone)
  439. next_run_time = job.trigger.get_next_fire_time(None, now)
  440. if next_run_time:
  441. return self.modify_job(job_id, jobstore, next_run_time=next_run_time)
  442. else:
  443. self.remove_job(job.id, jobstore)
  444. def get_jobs(self, jobstore=None, pending=None):
  445. """
  446. Returns a list of pending jobs (if the scheduler hasn't been started yet) and scheduled
  447. jobs, either from a specific job store or from all of them.
  448. If the scheduler has not been started yet, only pending jobs can be returned because the
  449. job stores haven't been started yet either.
  450. :param str|unicode jobstore: alias of the job store
  451. :param bool pending: **DEPRECATED**
  452. :rtype: list[Job]
  453. """
  454. if pending is not None:
  455. warnings.warn('The "pending" option is deprecated -- get_jobs() always returns '
  456. 'scheduled jobs if the scheduler has been started and pending jobs '
  457. 'otherwise', DeprecationWarning)
  458. with self._jobstores_lock:
  459. jobs = []
  460. if self.state == STATE_STOPPED:
  461. for job, alias, replace_existing in self._pending_jobs:
  462. if jobstore is None or alias == jobstore:
  463. jobs.append(job)
  464. else:
  465. for alias, store in six.iteritems(self._jobstores):
  466. if jobstore is None or alias == jobstore:
  467. jobs.extend(store.get_all_jobs())
  468. return jobs
  469. def get_job(self, job_id, jobstore=None):
  470. """
  471. Returns the Job that matches the given ``job_id``.
  472. :param str|unicode job_id: the identifier of the job
  473. :param str|unicode jobstore: alias of the job store that most likely contains the job
  474. :return: the Job by the given ID, or ``None`` if it wasn't found
  475. :rtype: Job
  476. """
  477. with self._jobstores_lock:
  478. try:
  479. return self._lookup_job(job_id, jobstore)[0]
  480. except JobLookupError:
  481. return
  482. def remove_job(self, job_id, jobstore=None):
  483. """
  484. Removes a job, preventing it from being run any more.
  485. :param str|unicode job_id: the identifier of the job
  486. :param str|unicode jobstore: alias of the job store that contains the job
  487. :raises JobLookupError: if the job was not found
  488. """
  489. jobstore_alias = None
  490. with self._jobstores_lock:
  491. # Check if the job is among the pending jobs
  492. if self.state == STATE_STOPPED:
  493. for i, (job, alias, replace_existing) in enumerate(self._pending_jobs):
  494. if job.id == job_id and jobstore in (None, alias):
  495. del self._pending_jobs[i]
  496. jobstore_alias = alias
  497. break
  498. else:
  499. # Otherwise, try to remove it from each store until it succeeds or we run out of
  500. # stores to check
  501. for alias, store in six.iteritems(self._jobstores):
  502. if jobstore in (None, alias):
  503. try:
  504. store.remove_job(job_id)
  505. jobstore_alias = alias
  506. break
  507. except JobLookupError:
  508. continue
  509. if jobstore_alias is None:
  510. raise JobLookupError(job_id)
  511. # Notify listeners that a job has been removed
  512. event = JobEvent(EVENT_JOB_REMOVED, job_id, jobstore_alias)
  513. self._dispatch_event(event)
  514. self._logger.info('Removed job %s', job_id)
  515. def remove_all_jobs(self, jobstore=None):
  516. """
  517. Removes all jobs from the specified job store, or all job stores if none is given.
  518. :param str|unicode jobstore: alias of the job store
  519. """
  520. with self._jobstores_lock:
  521. if self.state == STATE_STOPPED:
  522. if jobstore:
  523. self._pending_jobs = [pending for pending in self._pending_jobs if
  524. pending[1] != jobstore]
  525. else:
  526. self._pending_jobs = []
  527. else:
  528. for alias, store in six.iteritems(self._jobstores):
  529. if jobstore in (None, alias):
  530. store.remove_all_jobs()
  531. self._dispatch_event(SchedulerEvent(EVENT_ALL_JOBS_REMOVED, jobstore))
  532. def print_jobs(self, jobstore=None, out=None):
  533. """
  534. print_jobs(jobstore=None, out=sys.stdout)
  535. Prints out a textual listing of all jobs currently scheduled on either all job stores or
  536. just a specific one.
  537. :param str|unicode jobstore: alias of the job store, ``None`` to list jobs from all stores
  538. :param file out: a file-like object to print to (defaults to **sys.stdout** if nothing is
  539. given)
  540. """
  541. out = out or sys.stdout
  542. with self._jobstores_lock:
  543. if self.state == STATE_STOPPED:
  544. print(u'Pending jobs:', file=out)
  545. if self._pending_jobs:
  546. for job, jobstore_alias, replace_existing in self._pending_jobs:
  547. if jobstore in (None, jobstore_alias):
  548. print(u' %s' % job, file=out)
  549. else:
  550. print(u' No pending jobs', file=out)
  551. else:
  552. for alias, store in sorted(six.iteritems(self._jobstores)):
  553. if jobstore in (None, alias):
  554. print(u'Jobstore %s:' % alias, file=out)
  555. jobs = store.get_all_jobs()
  556. if jobs:
  557. for job in jobs:
  558. print(u' %s' % job, file=out)
  559. else:
  560. print(u' No scheduled jobs', file=out)
  561. @abstractmethod
  562. def wakeup(self):
  563. """
  564. Notifies the scheduler that there may be jobs due for execution.
  565. Triggers :meth:`_process_jobs` to be run in an implementation specific manner.
  566. """
  567. #
  568. # Private API
  569. #
  570. def _configure(self, config):
  571. # Set general options
  572. self._logger = maybe_ref(config.pop('logger', None)) or getLogger('apscheduler.scheduler')
  573. self.timezone = astimezone(config.pop('timezone', None)) or get_localzone()
  574. self.jobstore_retry_interval = float(config.pop('jobstore_retry_interval', 10))
  575. # Set the job defaults
  576. job_defaults = config.get('job_defaults', {})
  577. self._job_defaults = {
  578. 'misfire_grace_time': asint(job_defaults.get('misfire_grace_time', 1)),
  579. 'coalesce': asbool(job_defaults.get('coalesce', True)),
  580. 'max_instances': asint(job_defaults.get('max_instances', 1))
  581. }
  582. # Configure executors
  583. self._executors.clear()
  584. for alias, value in six.iteritems(config.get('executors', {})):
  585. if isinstance(value, BaseExecutor):
  586. self.add_executor(value, alias)
  587. elif isinstance(value, MutableMapping):
  588. executor_class = value.pop('class', None)
  589. plugin = value.pop('type', None)
  590. if plugin:
  591. executor = self._create_plugin_instance('executor', plugin, value)
  592. elif executor_class:
  593. cls = maybe_ref(executor_class)
  594. executor = cls(**value)
  595. else:
  596. raise ValueError(
  597. 'Cannot create executor "%s" -- either "type" or "class" must be defined' %
  598. alias)
  599. self.add_executor(executor, alias)
  600. else:
  601. raise TypeError(
  602. "Expected executor instance or dict for executors['%s'], got %s instead" %
  603. (alias, value.__class__.__name__))
  604. # Configure job stores
  605. self._jobstores.clear()
  606. for alias, value in six.iteritems(config.get('jobstores', {})):
  607. if isinstance(value, BaseJobStore):
  608. self.add_jobstore(value, alias)
  609. elif isinstance(value, MutableMapping):
  610. jobstore_class = value.pop('class', None)
  611. plugin = value.pop('type', None)
  612. if plugin:
  613. jobstore = self._create_plugin_instance('jobstore', plugin, value)
  614. elif jobstore_class:
  615. cls = maybe_ref(jobstore_class)
  616. jobstore = cls(**value)
  617. else:
  618. raise ValueError(
  619. 'Cannot create job store "%s" -- either "type" or "class" must be '
  620. 'defined' % alias)
  621. self.add_jobstore(jobstore, alias)
  622. else:
  623. raise TypeError(
  624. "Expected job store instance or dict for jobstores['%s'], got %s instead" %
  625. (alias, value.__class__.__name__))
  626. def _create_default_executor(self):
  627. """Creates a default executor store, specific to the particular scheduler type."""
  628. return ThreadPoolExecutor()
  629. def _create_default_jobstore(self):
  630. """Creates a default job store, specific to the particular scheduler type."""
  631. return MemoryJobStore()
  632. def _lookup_executor(self, alias):
  633. """
  634. Returns the executor instance by the given name from the list of executors that were added
  635. to this scheduler.
  636. :type alias: str
  637. :raises KeyError: if no executor by the given alias is not found
  638. """
  639. try:
  640. return self._executors[alias]
  641. except KeyError:
  642. raise KeyError('No such executor: %s' % alias)
  643. def _lookup_jobstore(self, alias):
  644. """
  645. Returns the job store instance by the given name from the list of job stores that were
  646. added to this scheduler.
  647. :type alias: str
  648. :raises KeyError: if no job store by the given alias is not found
  649. """
  650. try:
  651. return self._jobstores[alias]
  652. except KeyError:
  653. raise KeyError('No such job store: %s' % alias)
  654. def _lookup_job(self, job_id, jobstore_alias):
  655. """
  656. Finds a job by its ID.
  657. :type job_id: str
  658. :param str jobstore_alias: alias of a job store to look in
  659. :return tuple[Job, str]: a tuple of job, jobstore alias (jobstore alias is None in case of
  660. a pending job)
  661. :raises JobLookupError: if no job by the given ID is found.
  662. """
  663. if self.state == STATE_STOPPED:
  664. # Check if the job is among the pending jobs
  665. for job, alias, replace_existing in self._pending_jobs:
  666. if job.id == job_id:
  667. return job, None
  668. else:
  669. # Look in all job stores
  670. for alias, store in six.iteritems(self._jobstores):
  671. if jobstore_alias in (None, alias):
  672. job = store.lookup_job(job_id)
  673. if job is not None:
  674. return job, alias
  675. raise JobLookupError(job_id)
  676. def _dispatch_event(self, event):
  677. """
  678. Dispatches the given event to interested listeners.
  679. :param SchedulerEvent event: the event to send
  680. """
  681. with self._listeners_lock:
  682. listeners = tuple(self._listeners)
  683. for cb, mask in listeners:
  684. if event.code & mask:
  685. try:
  686. cb(event)
  687. except BaseException:
  688. self._logger.exception('Error notifying listener')
  689. def _check_uwsgi(self):
  690. """Check if we're running under uWSGI with threads disabled."""
  691. uwsgi_module = sys.modules.get('uwsgi')
  692. if not getattr(uwsgi_module, 'has_threads', True):
  693. raise RuntimeError('The scheduler seems to be running under uWSGI, but threads have '
  694. 'been disabled. You must run uWSGI with the --enable-threads '
  695. 'option for the scheduler to work.')
  696. def _real_add_job(self, job, jobstore_alias, replace_existing):
  697. """
  698. :param Job job: the job to add
  699. :param bool replace_existing: ``True`` to use update_job() in case the job already exists
  700. in the store
  701. """
  702. # Fill in undefined values with defaults
  703. replacements = {}
  704. for key, value in six.iteritems(self._job_defaults):
  705. if not hasattr(job, key):
  706. replacements[key] = value
  707. # Calculate the next run time if there is none defined
  708. if not hasattr(job, 'next_run_time'):
  709. now = datetime.now(self.timezone)
  710. replacements['next_run_time'] = job.trigger.get_next_fire_time(None, now)
  711. # Apply any replacements
  712. job._modify(**replacements)
  713. # Add the job to the given job store
  714. store = self._lookup_jobstore(jobstore_alias)
  715. try:
  716. store.add_job(job)
  717. except ConflictingIdError:
  718. if replace_existing:
  719. store.update_job(job)
  720. else:
  721. raise
  722. # Mark the job as no longer pending
  723. job._jobstore_alias = jobstore_alias
  724. # Notify listeners that a new job has been added
  725. event = JobEvent(EVENT_JOB_ADDED, job.id, jobstore_alias)
  726. self._dispatch_event(event)
  727. self._logger.info('Added job "%s" to job store "%s"', job.name, jobstore_alias)
  728. # Notify the scheduler about the new job
  729. if self.state == STATE_RUNNING:
  730. self.wakeup()
  731. def _create_plugin_instance(self, type_, alias, constructor_kwargs):
  732. """Creates an instance of the given plugin type, loading the plugin first if necessary."""
  733. plugin_container, class_container, base_class = {
  734. 'trigger': (self._trigger_plugins, self._trigger_classes, BaseTrigger),
  735. 'jobstore': (self._jobstore_plugins, self._jobstore_classes, BaseJobStore),
  736. 'executor': (self._executor_plugins, self._executor_classes, BaseExecutor)
  737. }[type_]
  738. try:
  739. plugin_cls = class_container[alias]
  740. except KeyError:
  741. if alias in plugin_container:
  742. plugin_cls = class_container[alias] = plugin_container[alias].load()
  743. if not issubclass(plugin_cls, base_class):
  744. raise TypeError('The {0} entry point does not point to a {0} class'.
  745. format(type_))
  746. else:
  747. raise LookupError('No {0} by the name "{1}" was found'.format(type_, alias))
  748. return plugin_cls(**constructor_kwargs)
  749. def _create_trigger(self, trigger, trigger_args):
  750. if isinstance(trigger, BaseTrigger):
  751. return trigger
  752. elif trigger is None:
  753. trigger = 'date'
  754. elif not isinstance(trigger, six.string_types):
  755. raise TypeError('Expected a trigger instance or string, got %s instead' %
  756. trigger.__class__.__name__)
  757. # Use the scheduler's time zone if nothing else is specified
  758. trigger_args.setdefault('timezone', self.timezone)
  759. # Instantiate the trigger class
  760. return self._create_plugin_instance('trigger', trigger, trigger_args)
  761. def _create_lock(self):
  762. """Creates a reentrant lock object."""
  763. return RLock()
  764. def _process_jobs(self):
  765. """
  766. Iterates through jobs in every jobstore, starts jobs that are due and figures out how long
  767. to wait for the next round.
  768. If the ``get_due_jobs()`` call raises an exception, a new wakeup is scheduled in at least
  769. ``jobstore_retry_interval`` seconds.
  770. """
  771. if self.state == STATE_PAUSED:
  772. self._logger.debug('Scheduler is paused -- not processing jobs')
  773. return None
  774. self._logger.debug('Looking for jobs to run')
  775. now = datetime.now(self.timezone)
  776. next_wakeup_time = None
  777. events = []
  778. with self._jobstores_lock:
  779. for jobstore_alias, jobstore in six.iteritems(self._jobstores):
  780. try:
  781. due_jobs = jobstore.get_due_jobs(now)
  782. except Exception as e:
  783. # Schedule a wakeup at least in jobstore_retry_interval seconds
  784. self._logger.warning('Error getting due jobs from job store %r: %s',
  785. jobstore_alias, e)
  786. retry_wakeup_time = now + timedelta(seconds=self.jobstore_retry_interval)
  787. if not next_wakeup_time or next_wakeup_time > retry_wakeup_time:
  788. next_wakeup_time = retry_wakeup_time
  789. continue
  790. for job in due_jobs:
  791. # Look up the job's executor
  792. try:
  793. executor = self._lookup_executor(job.executor)
  794. except BaseException:
  795. self._logger.error(
  796. 'Executor lookup ("%s") failed for job "%s" -- removing it from the '
  797. 'job store', job.executor, job)
  798. self.remove_job(job.id, jobstore_alias)
  799. continue
  800. run_times = job._get_run_times(now)
  801. run_times = run_times[-1:] if run_times and job.coalesce else run_times
  802. if run_times:
  803. try:
  804. executor.submit_job(job, run_times)
  805. except MaxInstancesReachedError:
  806. self._logger.warning(
  807. 'Execution of job "%s" skipped: maximum number of running '
  808. 'instances reached (%d)', job, job.max_instances)
  809. event = JobSubmissionEvent(EVENT_JOB_MAX_INSTANCES, job.id,
  810. jobstore_alias, run_times)
  811. events.append(event)
  812. except BaseException:
  813. self._logger.exception('Error submitting job "%s" to executor "%s"',
  814. job, job.executor)
  815. else:
  816. event = JobSubmissionEvent(EVENT_JOB_SUBMITTED, job.id, jobstore_alias,
  817. run_times)
  818. events.append(event)
  819. # Update the job if it has a next execution time.
  820. # Otherwise remove it from the job store.
  821. job_next_run = job.trigger.get_next_fire_time(run_times[-1], now)
  822. if job_next_run:
  823. job._modify(next_run_time=job_next_run)
  824. jobstore.update_job(job)
  825. else:
  826. self.remove_job(job.id, jobstore_alias)
  827. # Set a new next wakeup time if there isn't one yet or
  828. # the jobstore has an even earlier one
  829. jobstore_next_run_time = jobstore.get_next_run_time()
  830. if jobstore_next_run_time and (next_wakeup_time is None or
  831. jobstore_next_run_time < next_wakeup_time):
  832. next_wakeup_time = jobstore_next_run_time.astimezone(self.timezone)
  833. # Dispatch collected events
  834. for event in events:
  835. self._dispatch_event(event)
  836. # Determine the delay until this method should be called again
  837. if self.state == STATE_PAUSED:
  838. wait_seconds = None
  839. self._logger.debug('Scheduler is paused; waiting until resume() is called')
  840. elif next_wakeup_time is None:
  841. wait_seconds = None
  842. self._logger.debug('No jobs; waiting until a job is added')
  843. else:
  844. now = datetime.now(self.timezone)
  845. wait_seconds = min(max(timedelta_seconds(next_wakeup_time - now), 0), TIMEOUT_MAX)
  846. self._logger.debug('Next wakeup is due at %s (in %f seconds)', next_wakeup_time,
  847. wait_seconds)
  848. return wait_seconds