API reference

Data structures

class apscheduler.Task(*, id, func, job_executor, max_running_jobs=None, misfire_grace_time=None, metadata=NOTHING, running_jobs=0)

Represents a callable and its surrounding configuration parameters.

Variables:
  • id (str) – the unique identifier of this task

  • func (Callable) – the callable that is called when this task is run

  • job_executor (str) – name of the job executor that will run this task

  • max_running_jobs (int | None) – maximum number of instances of this task that are allowed to run concurrently

  • misfire_grace_time (timedelta | None) – maximum number of seconds the run time of jobs created for this task are allowed to be late, compared to the scheduled run time

  • metadata – key-value pairs for storing JSON compatible custom information

class apscheduler.TaskDefaults(*, job_executor=<unset>, max_running_jobs=1, misfire_grace_time=None, metadata=NOTHING)

Contains default values for tasks that will be applied when no matching configuration value has been explicitly provided.

Parameters:
  • job_executor (str | UnsetValue) – name of the job executor that will run this task

  • max_running_jobs (int | None | UnsetValue) – maximum number of instances of this task that are allowed to run concurrently

  • misfire_grace_time (timedelta | int) – maximum number of seconds the run time of jobs created for this task are allowed to be late, compared to the scheduled run time

Variables:

metadata – key-value pairs for storing JSON compatible custom information

class apscheduler.Schedule(*, id, task_id, trigger, args=(), kwargs=(), paused=False, coalesce=CoalescePolicy.latest, misfire_grace_time=None, max_jitter=None, job_executor, job_result_expiration_time=0, metadata=NOTHING, next_fire_time=None, last_fire_time=None, acquired_by=None, acquired_until=None)

Represents a schedule on which a task will be run.

Variables:
  • id (str) – the unique identifier of this schedule

  • task_id (str) – unique identifier of the task to be run on this schedule

  • trigger (Trigger) – the trigger that determines when the task will be run

  • args (tuple) – positional arguments to pass to the task callable

  • kwargs (dict[str, Any]) – keyword arguments to pass to the task callable

  • paused (bool) – whether the schedule is paused

  • coalesce (CoalescePolicy) – determines what to do when processing the schedule if multiple fire times have become due for this schedule since the last processing

  • misfire_grace_time (timedelta | None) – maximum number of seconds the scheduled job’s actual run time is allowed to be late, compared to the scheduled run time

  • max_jitter (timedelta | None) – maximum number of seconds to randomly add to the scheduled time for each job created from this schedule

  • job_result_expiration_time (timedelta) – minimum time to keep the job results in storage from the jobs created by this schedule

  • metadata – key-value pairs for storing JSON compatible custom information

  • next_fire_time (datetime) – the next time the task will be run

  • last_fire_time (datetime | None) – the last time the task was scheduled to run

  • acquired_by (str | None) – ID of the scheduler that has acquired this schedule for processing

  • acquired_until (str | None) – the time after which other schedulers are free to acquire the schedule for processing even if it is still marked as acquired

class apscheduler.ScheduleResult(*, schedule_id, task_id, trigger, last_fire_time, next_fire_time)

Represents a result of a schedule processing operation.

Variables:
  • schedule_id – ID of the schedule

  • task_id – ID of the schedule’s task

  • trigger – the schedule’s trigger

  • last_fire_time – the schedule’s trigger

  • next_fire_time – the next

class apscheduler.Job(*, id=NOTHING, task_id, args=(), kwargs=NOTHING, schedule_id=None, scheduled_fire_time=None, executor, jitter=NOTHING, start_deadline=None, result_expiration_time=datetime.timedelta(0), metadata=NOTHING, created_at=NOTHING, acquired_by=None, acquired_until=None)

Represents a queued request to run a task.

Variables:
  • id (UUID) – autogenerated unique identifier of the job

  • task_id (str) – unique identifier of the task to be run

  • args (tuple) – positional arguments to pass to the task callable

  • kwargs (dict[str, Any]) – keyword arguments to pass to the task callable

  • schedule_id (str) – unique identifier of the associated schedule (if the job was derived from a schedule)

  • scheduled_fire_time (datetime | None) – the time the job was scheduled to run at (if the job was derived from a schedule; includes jitter)

  • jitter (timedelta | None) – the time that was randomly added to the calculated scheduled run time (if the job was derived from a schedule)

  • start_deadline (datetime | None) – if the job is started in the scheduler after this time, it is considered to be misfired and will be aborted

  • result_expiration_time (timedelta) – minimum amount of time to keep the result available for fetching in the data store

  • metadata – key-value pairs for storing JSON compatible custom information

  • created_at (datetime) – the time at which the job was created

  • acquired_by (str | None) – the unique identifier of the scheduler that has acquired the job for execution

  • acquired_until (str | None) – the time after which other schedulers are free to acquire the job for processing even if it is still marked as acquired

property original_scheduled_time: TypeAliasForwardRef('datetime.datetime') | None

The scheduled time without any jitter included.

class apscheduler.JobResult(*, job_id, outcome, started_at=None, finished_at, expires_at, exception=None, return_value=None)

Represents the result of running a job.

Variables:
  • job_id (UUID) – the unique identifier of the job

  • outcome (JobOutcome) – indicates how the job ended

  • started_at (datetime) – the time when the job was submitted to the executor (None if the job never started in the first place)

  • finished_at (datetime) – the time when the job finished running, or was discarded during the job acquisition process

  • expires_at (datetime) – the time when the result will expire

  • exception (BaseException | None) – the exception object if the job ended due to an exception being raised

  • return_value – the return value from the task function (if the job ran to completion successfully)

Decorators

@apscheduler.task(id=<unset>, *, job_executor=<unset>, max_running_jobs=<unset>, misfire_grace_time=<unset>, metadata=<unset>)

Decorate a function to have implied defaults as an APScheduler task.

Parameters:
Return type:

Callable[[TypeVar(T, bound= Callable[…, Any])], TypeVar(T, bound= Callable[…, Any])]

Schedulers

class apscheduler.Scheduler(data_store=None, event_broker=None, *, identity='', role=SchedulerRole.both, max_concurrent_jobs=100, cleanup_interval=None, lease_duration=datetime.timedelta(seconds=30), job_executors=None, task_defaults=None, logger=None)

A synchronous wrapper for AsyncScheduler.

When started, this wrapper launches an asynchronous event loop in a separate thread and runs the asynchronous scheduler there. This thread is shut down along with the scheduler.

See the documentation of the AsyncScheduler class for the documentation of the configuration options.

add_job(func_or_task_id, *, args=None, kwargs=None, job_executor=<unset>, metadata=<unset>, result_expiration_time=0)

Add a job to the data store.

Parameters:
  • func_or_task_id (Task | str | Callable[..., Any]) – Either the ID of a pre-existing task, or a function/method. If a function is given, a task will be created with the fully qualified name of the function as the task ID (unless that task already exists of course).

  • args (Iterable[Any] | None) – positional arguments to call the target callable with

  • kwargs (Mapping[str, Any] | None) – keyword arguments to call the target callable with

  • job_executor (str | UnsetValue) – name of the job executor to run the task with (overrides the executor in the task definition, if any)

  • metadata (dict[str, str | int | bool | None | list[dict[str, str | int | bool | None | list[MetadataType] | dict[str, MetadataType]]] | dict[str, dict[str, str | int | bool | None | list[MetadataType] | dict[str, MetadataType]]]] | UnsetValue) – key-value pairs for storing JSON compatible custom information

  • result_expiration_time (timedelta | float) – the minimum time (as seconds, or timedelta) to keep the result of the job available for fetching (the result won’t be saved at all if that time is 0)

Return type:

uuid.UUID

Returns:

the ID of the newly created job

add_schedule(func_or_task_id, trigger, *, id=None, args=None, kwargs=None, paused=False, coalesce=CoalescePolicy.latest, job_executor=<unset>, misfire_grace_time=<unset>, metadata=<unset>, max_jitter=None, job_result_expiration_time=0, conflict_policy=ConflictPolicy.do_nothing)

Schedule a task to be run one or more times in the future.

Parameters:
  • func_or_task_id (Task | str | Callable[..., Any]) – either a callable or an ID of an existing task definition

  • trigger (Trigger) – determines the times when the task should be run

  • id (str | None) – an explicit identifier for the schedule (if omitted, a random, UUID based ID will be assigned)

  • args (Iterable[Any] | None) – positional arguments to be passed to the task function

  • kwargs (Mapping[str, Any] | None) – keyword arguments to be passed to the task function

  • paused (bool) – whether the schedule is paused

  • job_executor (str | UnsetValue) – name of the job executor to run the scheduled jobs with (overrides the executor specified in the task settings)

  • coalesce (CoalescePolicy) – determines what to do when processing the schedule if multiple fire times have become due for this schedule since the last processing

  • misfire_grace_time (float | timedelta | None | UnsetValue) – maximum number of seconds the scheduled job’s actual run time is allowed to be late, compared to the scheduled run time

  • metadata (dict[str, str | int | bool | None | list[dict[str, str | int | bool | None | list[MetadataType] | dict[str, MetadataType]]] | dict[str, dict[str, str | int | bool | None | list[MetadataType] | dict[str, MetadataType]]]] | UnsetValue) – key-value pairs for storing JSON compatible custom information

  • max_jitter (float | timedelta | None) – maximum time (in seconds, or as a timedelta) to randomly add to the scheduled time for each job created from this schedule

  • job_result_expiration_time (float | timedelta) – minimum time (in seconds, or as a timedelta) to keep the job results in storage from the jobs created by this schedule

  • conflict_policy (ConflictPolicy) – determines what to do if a schedule with the same ID already exists in the data store

Return type:

str

Returns:

the ID of the newly added schedule

cleanup()

Clean up expired job results and finished schedules.

Return type:

None

configure_task(func_or_task_id, *, func=<unset>, job_executor=<unset>, misfire_grace_time=<unset>, max_running_jobs=<unset>, metadata=<unset>)

Add or update a task definition.

Any options not explicitly passed to this method will use their default values (from task_defaults) when a new task is created:

  • job_executor: the value of default_job_executor scheduler attribute

  • misfire_grace_time: None

  • max_running_jobs: 1

When updating a task, any options not explicitly passed will remain the same.

If a callable is passed as the first argument, its fully qualified name will be used as the task ID.

Parameters:
Raises:

TypeError – if func_or_task_id is neither a task, task ID or a callable

Return type:

Task

Returns:

the created or updated task definition

get_job_result(job_id, *, wait=True)

Retrieve the result of a job.

Parameters:
  • job_id (uuid.UUID) – the ID of the job

  • wait (bool) – if True, wait until the job has ended (one way or another), False to raise an exception if the result is not yet available

Return type:

JobResult | None

Returns:

the job result, or None if the job finished but didn’t record a result (result_expiration_time was 0 or a similarly short time interval that did not allow for the result to be fetched before it was deleted)

Raises:

JobLookupError – if neither the job or its result exist in the data store, or the job exists but the result is not ready yet and wait=False is set

get_jobs()

Retrieve all jobs from the data store.

Return type:

Sequence[Job]

get_next_event(event_types)
Overloads:
  • self, event_types (type[T_Event]) → T_Event

  • self, event_types (Iterable[type[Event]]) → Event

Wait until the next event matching one of the given types arrives.

Parameters:

event_types (type[Event] | Iterable[type[Event]]) – an event class or an iterable event classes to subscribe to

get_schedule(id)

Retrieve a schedule from the data store.

Parameters:

id (str) – the unique identifier of the schedule

Raises:

ScheduleLookupError – if the schedule could not be found

Return type:

Schedule

get_schedules()

Retrieve all schedules from the data store.

Return type:

list[Schedule]

Returns:

a list of schedules, in an unspecified order

get_tasks()

Retrieve all currently defined tasks.

Return type:

Sequence[Task]

Returns:

a sequence of tasks, sorted by ID

pause_schedule(id)

Pause the specified schedule.

Return type:

None

remove_schedule(id)

Remove the given schedule from the data store.

Parameters:

id (str) – the unique identifier of the schedule

Return type:

None

run_job(func_or_task_id, *, args=None, kwargs=None, job_executor=<unset>, metadata=<unset>)

Convenience method to add a job and then return its result.

If the job raised an exception, that exception will be reraised here.

Parameters:
Return type:

Any

Returns:

the return value of the task function

run_until_stopped()

Run the scheduler until explicitly stopped.

Return type:

None

start_in_background()

Launch the scheduler in a new thread.

This method registers atexit hooks to shut down the scheduler and wait for the thread to finish.

Raises:

RuntimeError – if the scheduler is not in the stopped state

Return type:

None

property state: RunState

The current running state of the scheduler.

stop()

Signal the scheduler that it should stop processing schedules.

This method does not wait for the scheduler to actually stop. For that, see wait_until_stopped().

Return type:

None

subscribe(callback, event_types=None, *, one_shot=False)
Overloads:
  • self, callback (Callable[[T_Event], Any]), event_types (type[T_Event]), one_shot (bool) → Subscription

  • self, callback (Callable[[Event], Any]), event_types (Iterable[type[Event]] | None), one_shot (bool) → Subscription

Subscribe to events.

To unsubscribe, call the unsubscribe() method on the returned object.

Parameters:
  • callback (Callable[[TypeVar(T_Event, bound= Event)], Any]) – callable to be called with the event object when an event is published

  • event_types (type[TypeVar(T_Event, bound= Event)] | Iterable[type[TypeVar(T_Event, bound= Event)]] | None) – an iterable of concrete Event classes to subscribe to

  • one_shot (bool) – if True, automatically unsubscribe after the first matching event

unpause_schedule(id, *, resume_from=None)

Unpause the specified schedule.

Parameters:

resume_from (Union[datetime.datetime, Literal['now'], None]) – the time to resume the schedules from, or 'now' as a shorthand for datetime.now(tz=UTC) or None to resume from where the schedule left off which may cause it to misfire

Return type:

None

wait_until_stopped()

Wait until the scheduler is in the stopped or stopping state.

If the scheduler is already stopped or in the process of stopping, this method returns immediately. Otherwise, it waits until the scheduler posts the SchedulerStopped event.

Return type:

None

class apscheduler.AsyncScheduler(data_store=NOTHING, event_broker=NOTHING, lease_duration=30, *, identity='', role=SchedulerRole.both, task_defaults=NOTHING, max_concurrent_jobs=100, job_executors=NOTHING, cleanup_interval=datetime.timedelta(seconds=900), logger=<Logger apscheduler._schedulers.async_ (WARNING)>)

An asynchronous (AnyIO based) scheduler implementation.

Requires either asyncio or Trio to work.

Note

If running on Trio, ensure that the data store and event broker are compatible with Trio.

Parameters:
  • data_store (DataStore) – the data store for tasks, schedules and jobs

  • event_broker (EventBroker) – the event broker to use for publishing an subscribing events

  • identity (str) – the unique identifier of the scheduler

  • role (Any) – specifies what the scheduler should be doing when running (scheduling only, job running only, or both)

  • max_concurrent_jobs (int) – Maximum number of jobs the scheduler will run at once

  • job_executors (MutableMapping[str, JobExecutor]) – a mutable mapping of executor names to executor instances

  • task_defaults (TaskDefaults) – default settings for newly configured tasks

  • cleanup_interval (timedelta | int) – interval (as seconds or timedelta) between automatic calls to cleanup()None to disable automatic clean-up

  • lease_duration (timedelta | int) – maximum amount of time (as seconds or timedelta) that the scheduler can keep a lock on a schedule or task

  • logger (Logger) – the logger instance used to log events from the scheduler, data store and event broker

async add_job(func_or_task_id, *, args=None, kwargs=None, job_executor=<unset>, metadata=<unset>, result_expiration_time=0)

Add a job to the data store.

Parameters:
  • func_or_task_id (Task | str | Callable[..., Any]) – Either the ID of a pre-existing task, or a function/method. If a function is given, a task will be created with the fully qualified name of the function as the task ID (unless that task already exists of course).

  • args (Iterable[Any] | None) – positional arguments to call the target callable with

  • kwargs (Mapping[str, Any] | None) – keyword arguments to call the target callable with

  • job_executor (str | UnsetValue) – name of the job executor to run the task with (overrides the executor in the task definition, if any)

  • metadata (dict[str, str | int | bool | None | list[dict[str, str | int | bool | None | list[MetadataType] | dict[str, MetadataType]]] | dict[str, dict[str, str | int | bool | None | list[MetadataType] | dict[str, MetadataType]]]] | UnsetValue) – key-value pairs for storing JSON compatible custom information

  • result_expiration_time (timedelta | float) – the minimum time (as seconds, or timedelta) to keep the result of the job available for fetching (the result won’t be saved at all if that time is 0)

Return type:

uuid.UUID

Returns:

the ID of the newly created job

async add_schedule(func_or_task_id, trigger, *, id=None, args=None, kwargs=None, paused=False, coalesce=CoalescePolicy.latest, job_executor=<unset>, misfire_grace_time=<unset>, metadata=<unset>, max_jitter=None, job_result_expiration_time=0, conflict_policy=ConflictPolicy.do_nothing)

Schedule a task to be run one or more times in the future.

Parameters:
  • func_or_task_id (Task | str | Callable[..., Any]) – either a callable or an ID of an existing task definition

  • trigger (Trigger) – determines the times when the task should be run

  • id (str | None) – an explicit identifier for the schedule (if omitted, a random, UUID based ID will be assigned)

  • args (Iterable[Any] | None) – positional arguments to be passed to the task function

  • kwargs (Mapping[str, Any] | None) – keyword arguments to be passed to the task function

  • paused (bool) – whether the schedule is paused

  • job_executor (str | UnsetValue) – name of the job executor to run the scheduled jobs with (overrides the executor specified in the task settings)

  • coalesce (CoalescePolicy) – determines what to do when processing the schedule if multiple fire times have become due for this schedule since the last processing

  • misfire_grace_time (float | timedelta | None | UnsetValue) – maximum number of seconds the scheduled job’s actual run time is allowed to be late, compared to the scheduled run time

  • metadata (dict[str, str | int | bool | None | list[dict[str, str | int | bool | None | list[MetadataType] | dict[str, MetadataType]]] | dict[str, dict[str, str | int | bool | None | list[MetadataType] | dict[str, MetadataType]]]] | UnsetValue) – key-value pairs for storing JSON compatible custom information

  • max_jitter (float | timedelta | None) – maximum time (in seconds, or as a timedelta) to randomly add to the scheduled time for each job created from this schedule

  • job_result_expiration_time (float | timedelta) – minimum time (in seconds, or as a timedelta) to keep the job results in storage from the jobs created by this schedule

  • conflict_policy (ConflictPolicy) – determines what to do if a schedule with the same ID already exists in the data store

Return type:

str

Returns:

the ID of the newly added schedule

async cleanup()

Clean up expired job results and finished schedules.

Return type:

None

async configure_task(func_or_task_id, *, func=<unset>, job_executor=<unset>, misfire_grace_time=<unset>, max_running_jobs=<unset>, metadata=<unset>)

Add or update a task definition.

Any options not explicitly passed to this method will use their default values (from task_defaults) when a new task is created:

  • job_executor: the value of default_job_executor scheduler attribute

  • misfire_grace_time: None

  • max_running_jobs: 1

When updating a task, any options not explicitly passed will remain the same.

If a callable is passed as the first argument, its fully qualified name will be used as the task ID.

Parameters:
Raises:

TypeError – if func_or_task_id is neither a task, task ID or a callable

Return type:

Task

Returns:

the created or updated task definition

async get_job_result(job_id, *, wait=True)

Retrieve the result of a job.

Parameters:
  • job_id (uuid.UUID) – the ID of the job

  • wait (bool) – if True, wait until the job has ended (one way or another), False to raise an exception if the result is not yet available

Return type:

JobResult | None

Returns:

the job result, or None if the job finished but didn’t record a result (result_expiration_time was 0 or a similarly short time interval that did not allow for the result to be fetched before it was deleted)

Raises:

JobLookupError – if neither the job or its result exist in the data store, or the job exists but the result is not ready yet and wait=False is set

async get_jobs()

Retrieve all jobs from the data store.

Return type:

Sequence[Job]

async get_next_event(event_types)
Overloads:
  • self, event_types (type[T_Event]) → T_Event

  • self, event_types (Iterable[type[Event]]) → Event

Wait until the next event matching one of the given types arrives.

Parameters:

event_types (type[Event] | Iterable[type[Event]]) – an event class or an iterable event classes to subscribe to

async get_schedule(id)

Retrieve a schedule from the data store.

Parameters:

id (str) – the unique identifier of the schedule

Raises:

ScheduleLookupError – if the schedule could not be found

Return type:

Schedule

async get_schedules()

Retrieve all schedules from the data store.

Return type:

list[Schedule]

Returns:

a list of schedules, in an unspecified order

async get_tasks()

Retrieve all currently defined tasks.

Return type:

Sequence[Task]

Returns:

a sequence of tasks, sorted by ID

async pause_schedule(id)

Pause the specified schedule.

Return type:

None

async remove_schedule(id)

Remove the given schedule from the data store.

Parameters:

id (str) – the unique identifier of the schedule

Return type:

None

async run_job(func_or_task_id, *, args=None, kwargs=None, job_executor=<unset>, metadata=<unset>)

Convenience method to add a job and then return its result.

If the job raised an exception, that exception will be reraised here.

Parameters:
Return type:

Any

Returns:

the return value of the task function

async run_until_stopped(*, task_status=<anyio._core._tasks._IgnoredTaskStatus object>)

Run the scheduler until explicitly stopped.

Return type:

None

property state: RunState

The current running state of the scheduler.

async stop()

Signal the scheduler that it should stop processing schedules.

This method does not wait for the scheduler to actually stop. For that, see wait_until_stopped().

Return type:

None

subscribe(callback, event_types=None, *, one_shot=False, is_async=True)
Overloads:
  • self, callback (Callable[[T_Event], Any]), event_types (type[T_Event]), one_shot (bool), is_async (bool) → Subscription

  • self, callback (Callable[[Event], Any]), event_types (Iterable[type[Event]] | None), one_shot (bool), is_async (bool) → Subscription

Subscribe to events.

To unsubscribe, call the unsubscribe() method on the returned object.

Parameters:
  • callback (Callable[[TypeVar(T_Event, bound= Event)], Any]) – callable to be called with the event object when an event is published

  • event_types (type[TypeVar(T_Event, bound= Event)] | Iterable[type[TypeVar(T_Event, bound= Event)]] | None) – an event class or an iterable event classes to subscribe to

  • one_shot (bool) – if True, automatically unsubscribe after the first matching event

  • is_async (bool) – True if the (synchronous) callback should be called on the event loop thread, False if it should be called in a worker thread. If callback is a coroutine function, this flag is ignored.

async unpause_schedule(id, *, resume_from=None)

Unpause the specified schedule.

Parameters:

resume_from (Union[datetime.datetime, Literal['now'], None]) – the time to resume the schedules from, or 'now' as a shorthand for datetime.now(tz=UTC) or None to resume from where the schedule left off which may cause it to misfire

Return type:

None

async wait_until_stopped()

Wait until the scheduler is in the stopped or stopping state.

If the scheduler is already stopped or in the process of stopping, this method returns immediately. Otherwise, it waits until the scheduler posts the SchedulerStopped event.

Return type:

None

Job executors

class apscheduler.abc.JobExecutor
abstractmethod async run_job(func, job)

Run the given job by calling the given function.

Parameters:
  • func (Callable[..., Any]) – the function to call

  • job (Job) – the associated job

Return type:

Any

Returns:

the return value of func (potentially awaiting on the returned aawaitable, if any)

async start(exit_stack)

Start the job executor.

Parameters:

exit_stack (AsyncExitStack) – an asynchronous exit stack which will be processed when the scheduler is shut down

Return type:

None

class apscheduler.executors.async_.AsyncJobExecutor

Executes functions directly on the event loop thread.

If the function returns a coroutine object (or another kind of awaitable), that is awaited on and its return value is used as the job’s return value.

async run_job(func, job)

Run the given job by calling the given function.

Parameters:
  • func (Callable[..., Any]) – the function to call

  • job (Job) – the associated job

Return type:

Any

Returns:

the return value of func (potentially awaiting on the returned aawaitable, if any)

class apscheduler.executors.subprocess.ProcessPoolJobExecutor(*, max_workers=40)

Executes functions in a process pool.

Parameters:

max_workers (int) – the maximum number of worker processes to keep

async run_job(func, job)

Run the given job by calling the given function.

Parameters:
  • func (Callable[..., Any]) – the function to call

  • job (Job) – the associated job

Return type:

Any

Returns:

the return value of func (potentially awaiting on the returned aawaitable, if any)

async start(exit_stack)

Start the job executor.

Parameters:

exit_stack (AsyncExitStack) – an asynchronous exit stack which will be processed when the scheduler is shut down

Return type:

None

class apscheduler.executors.qt.QtJobExecutor
async run_job(func, job)

Run the given job by calling the given function.

Parameters:
Return type:

Any

Returns:

the return value of func (potentially awaiting on the returned aawaitable, if any)

async start(exit_stack)

Start the job executor.

Parameters:

exit_stack (AsyncExitStack) – an asynchronous exit stack which will be processed when the scheduler is shut down

Return type:

None

class apscheduler.executors.thread.ThreadPoolJobExecutor(*, max_workers=40)

Executes functions in a thread pool.

Parameters:

max_workers (int) – the maximum number of worker threads to keep

async run_job(func, job)

Run the given job by calling the given function.

Parameters:
  • func (Callable[..., Any]) – the function to call

  • job (Job) – the associated job

Return type:

Any

Returns:

the return value of func (potentially awaiting on the returned aawaitable, if any)

async start(exit_stack)

Start the job executor.

Parameters:

exit_stack (AsyncExitStack) – an asynchronous exit stack which will be processed when the scheduler is shut down

Return type:

None

Data stores

class apscheduler.abc.DataStore

Interface for data stores.

Data stores keep track of tasks, schedules and jobs. When these objects change, the data store publishes events to the associated event broker accordingly.

abstractmethod async acquire_jobs(scheduler_id, lease_duration, limit=None)

Acquire unclaimed jobs for execution.

This method claims up to the requested number of jobs for the given scheduler and returns them.

Parameters:
  • scheduler_id (str) – unique identifier of the scheduler

  • lease_duration (timedelta) – the duration of the lease, after which the jobs will be considered to be dead if the scheduler doesn’t extend the lease duration

  • limit (int | None) – maximum number of jobs to claim and return

Return type:

list[Job]

Returns:

the list of claimed jobs

abstractmethod async acquire_schedules(scheduler_id, lease_duration, limit)

Acquire unclaimed due schedules for processing.

This method claims up to the requested number of schedules for the given scheduler and returns them.

For a stored schedule to be eligible for acquisition, it must fulfill one of the following conditions:

  • It is unclaimed (acquired_until is None)

  • Its claim has expired (acquired_until is less than the current datetime)

  • It is claimed by the given scheduler (acquired_by equals scheduler_id)

Parameters:
  • scheduler_id (str) – unique identifier of the scheduler

  • lease_duration (timedelta) – the duration of the lease, after which the schedules can be acquired by another scheduler even if acquired_by is not None

  • limit (int) – maximum number of schedules to claim

Return type:

list[Schedule]

Returns:

the list of claimed schedules

abstractmethod async add_job(job)

Add a job to be executed by an eligible scheduler.

Parameters:

job (Job) – the job object

Return type:

None

abstractmethod async add_schedule(schedule, conflict_policy)

Add or update the given schedule in the data store.

Parameters:
  • schedule (Schedule) – schedule to be added

  • conflict_policy (ConflictPolicy) – policy that determines what to do if there is an existing schedule with the same ID

Return type:

None

abstractmethod async add_task(task)

Add the given task to the store.

If a task with the same ID already exists, it replaces the old one but does NOT affect task accounting (# of running jobs).

Parameters:

task (Task) – the task to be added

Return type:

None

abstractmethod async cleanup()

Perform clean-up operations on the data store.

This method must perform the following operations (in this order):

  • Purge expired job results (where expires_at is less or equal to the current time)

  • Release jobs with expired leases with the cancelled outcome

  • Purge finished schedules (where next_run_time is None) that have no running jobs associated with them

Return type:

None

abstractmethod async extend_acquired_job_leases(scheduler_id, job_ids, duration)

Extend the leases of specified jobs acquired by the given scheduler.

Parameters:
  • scheduler_id (str) – unique identifier of the scheduler

  • job_ids (set[uuid.UUID]) – the identifiers of the jobs the scheduler is running

  • duration (timedelta) – the duration by which to extend the leases

Return type:

None

abstractmethod async extend_acquired_schedule_leases(scheduler_id, schedule_ids, duration)

Extend the leases of specified schedules acquired by the given scheduler.

Parameters:
  • scheduler_id (str) – unique identifier of the scheduler

  • schedule_ids (set[str]) – the identifiers of the schedules the scheduler is currently processing

  • duration (timedelta) – the duration by which to extend the leases

Return type:

None

abstractmethod async get_job_result(job_id)

Retrieve the result of a job.

The result is removed from the store after retrieval.

Parameters:

job_id (uuid.UUID) – the identifier of the job

Return type:

JobResult | None

Returns:

the result, or None if the result was not found

abstractmethod async get_jobs(ids=None)

Get the list of pending jobs.

Parameters:

ids (Iterable[uuid.UUID] | None) – a specific set of job IDs to return, or None to return all jobs

Return type:

list[Job]

Returns:

the list of matching pending jobs, in the order they will be given to schedulers

abstractmethod async get_next_schedule_run_time()

Return the earliest upcoming run time of all the schedules in the store, or None if there are no active schedules.

Return type:

Optional[datetime.datetime]

abstractmethod async get_schedules(ids=None)

Get schedules from the data store.

Parameters:

ids (set[str] | None) – a specific set of schedule IDs to return, or None to return all schedules

Return type:

list[Schedule]

Returns:

the list of matching schedules, in unspecified order

abstractmethod async get_task(task_id)

Get an existing task definition.

Parameters:

task_id (str) – ID of the task to be returned

Return type:

Task

Returns:

the matching task

Raises:

TaskLookupError – if no matching task was found

abstractmethod async get_tasks()

Get all the tasks in this store.

Return type:

list[Task]

Returns:

a list of tasks, sorted by ID

abstractmethod async reap_abandoned_jobs(scheduler_id)

Find jobs marked as acquired by the given scheduler ID and release them with the outcome of abandoned.

Implementers must ensure that the proper JobReleased events are published.

This method is called once during the scheduler startup sequence.

Parameters:

scheduler_id (str) – unique identifier of the scheduler

Return type:

None

abstractmethod async release_job(scheduler_id, job, result)

Release the claim on the given job and record the result.

Parameters:
  • scheduler_id (str) – unique identifier of the scheduler

  • job (Job) – the job to be released

  • result (JobResult) – the result of the job

Return type:

None

abstractmethod async release_schedules(scheduler_id, results)

Release the claims on the given schedules and update them on the store.

The data store is responsible for updating the following fields on stored schedules:

  • last_fire_time

  • next_fire_time

  • trigger

  • acquired_by (must beset to None)

  • acquired_until (must be set to None)

Parameters:
  • scheduler_id (str) – unique identifier of the scheduler

  • results (Sequence[ScheduleResult]) – list of schedule processing results

Return type:

None

abstractmethod async remove_schedules(ids)

Remove schedules from the data store.

Parameters:

ids (Iterable[str]) – a specific set of schedule IDs to remove

Return type:

None

abstractmethod async remove_task(task_id)

Remove the task with the given ID.

Parameters:

task_id (str) – ID of the task to be removed

Raises:

TaskLookupError – if no matching task was found

Return type:

None

abstractmethod async start(exit_stack, event_broker, logger)

Start the event broker.

Parameters:
  • exit_stack (AsyncExitStack) – an asynchronous exit stack which will be processed when the scheduler is shut down

  • event_broker (EventBroker) – the event broker shared between the scheduler, scheduler (if any) and this data store

  • logger (Logger) – the logger object the data store should use to log events

Return type:

None

class apscheduler.datastores.memory.MemoryDataStore(tasks=NOTHING, schedules=NOTHING, schedules_by_id=NOTHING, schedules_by_task_id=NOTHING, jobs_by_id=NOTHING, jobs_by_task_id=NOTHING, jobs_by_schedule_id=NOTHING, job_results=NOTHING)

Stores scheduler data in memory, without serializing it.

Can be shared between multiple schedulers within the same event loop.

async acquire_jobs(scheduler_id, lease_duration, limit=None)

Acquire unclaimed jobs for execution.

This method claims up to the requested number of jobs for the given scheduler and returns them.

Parameters:
  • scheduler_id (str) – unique identifier of the scheduler

  • lease_duration (timedelta) – the duration of the lease, after which the jobs will be considered to be dead if the scheduler doesn’t extend the lease duration

  • limit (int | None) – maximum number of jobs to claim and return

Return type:

list[Job]

Returns:

the list of claimed jobs

async acquire_schedules(scheduler_id, lease_duration, limit)

Acquire unclaimed due schedules for processing.

This method claims up to the requested number of schedules for the given scheduler and returns them.

For a stored schedule to be eligible for acquisition, it must fulfill one of the following conditions:

  • It is unclaimed (acquired_until is None)

  • Its claim has expired (acquired_until is less than the current datetime)

  • It is claimed by the given scheduler (acquired_by equals scheduler_id)

Parameters:
  • scheduler_id (str) – unique identifier of the scheduler

  • lease_duration (timedelta) – the duration of the lease, after which the schedules can be acquired by another scheduler even if acquired_by is not None

  • limit (int) – maximum number of schedules to claim

Return type:

list[Schedule]

Returns:

the list of claimed schedules

async add_job(job)

Add a job to be executed by an eligible scheduler.

Parameters:

job (Job) – the job object

Return type:

None

async add_schedule(schedule, conflict_policy)

Add or update the given schedule in the data store.

Parameters:
  • schedule (Schedule) – schedule to be added

  • conflict_policy (ConflictPolicy) – policy that determines what to do if there is an existing schedule with the same ID

Return type:

None

async add_task(task)

Add the given task to the store.

If a task with the same ID already exists, it replaces the old one but does NOT affect task accounting (# of running jobs).

Parameters:

task (Task) – the task to be added

Return type:

None

async cleanup()

Perform clean-up operations on the data store.

This method must perform the following operations (in this order):

  • Purge expired job results (where expires_at is less or equal to the current time)

  • Release jobs with expired leases with the cancelled outcome

  • Purge finished schedules (where next_run_time is None) that have no running jobs associated with them

Return type:

None

async extend_acquired_job_leases(scheduler_id, job_ids, duration)

Extend the leases of specified jobs acquired by the given scheduler.

Parameters:
  • scheduler_id (str) – unique identifier of the scheduler

  • job_ids (set[uuid.UUID]) – the identifiers of the jobs the scheduler is running

  • duration (timedelta) – the duration by which to extend the leases

Return type:

None

async extend_acquired_schedule_leases(scheduler_id, schedule_ids, duration)

Extend the leases of specified schedules acquired by the given scheduler.

Parameters:
  • scheduler_id (str) – unique identifier of the scheduler

  • schedule_ids (set[str]) – the identifiers of the schedules the scheduler is currently processing

  • duration (timedelta) – the duration by which to extend the leases

Return type:

None

async get_job_result(job_id)

Retrieve the result of a job.

The result is removed from the store after retrieval.

Parameters:

job_id (uuid.UUID) – the identifier of the job

Return type:

JobResult | None

Returns:

the result, or None if the result was not found

async get_jobs(ids=None)

Get the list of pending jobs.

Parameters:

ids (Iterable[uuid.UUID] | None) – a specific set of job IDs to return, or None to return all jobs

Return type:

list[Job]

Returns:

the list of matching pending jobs, in the order they will be given to schedulers

async get_next_schedule_run_time()

Return the earliest upcoming run time of all the schedules in the store, or None if there are no active schedules.

Return type:

Optional[datetime.datetime]

async get_schedules(ids=None)

Get schedules from the data store.

Parameters:

ids (set[str] | None) – a specific set of schedule IDs to return, or None to return all schedules

Return type:

list[Schedule]

Returns:

the list of matching schedules, in unspecified order

async get_task(task_id)

Get an existing task definition.

Parameters:

task_id (str) – ID of the task to be returned

Return type:

Task

Returns:

the matching task

Raises:

TaskLookupError – if no matching task was found

async get_tasks()

Get all the tasks in this store.

Return type:

list[Task]

Returns:

a list of tasks, sorted by ID

async reap_abandoned_jobs(scheduler_id)

Find jobs marked as acquired by the given scheduler ID and release them with the outcome of abandoned.

Implementers must ensure that the proper JobReleased events are published.

This method is called once during the scheduler startup sequence.

Parameters:

scheduler_id (str) – unique identifier of the scheduler

Return type:

None

async release_job(scheduler_id, job, result)

Release the claim on the given job and record the result.

Parameters:
  • scheduler_id (str) – unique identifier of the scheduler

  • job (Job) – the job to be released

  • result (JobResult) – the result of the job

Return type:

None

async release_schedules(scheduler_id, results)

Release the claims on the given schedules and update them on the store.

The data store is responsible for updating the following fields on stored schedules:

  • last_fire_time

  • next_fire_time

  • trigger

  • acquired_by (must beset to None)

  • acquired_until (must be set to None)

Parameters:
  • scheduler_id (str) – unique identifier of the scheduler

  • results (Sequence[ScheduleResult]) – list of schedule processing results

Return type:

None

async remove_schedules(ids, *, finished=False)

Remove schedules from the data store.

Parameters:

ids (Iterable[str]) – a specific set of schedule IDs to remove

Return type:

None

async remove_task(task_id)

Remove the task with the given ID.

Parameters:

task_id (str) – ID of the task to be removed

Raises:

TaskLookupError – if no matching task was found

Return type:

None

class apscheduler.datastores.sqlalchemy.SQLAlchemyDataStore(engine_or_url, *, retry_settings=RetrySettings(stop=<tenacity.stop.stop_after_delay object>, wait=<tenacity.wait.wait_exponential object>), serializer=NOTHING, start_from_scratch=False, schema=None)

Uses a relational database to store data.

When started, this data store creates the appropriate tables on the given database if they’re not already present.

Operations are retried (in accordance to retry_settings) when an operation raises either OSError or sqlalchemy.exc.InterfaceError.

This store has been tested to work with:

  • PostgreSQL (asyncpg and psycopg drivers)

  • MySQL (asyncmy driver)

  • aiosqlite (not recommended right now, as issues like #1032 exist)

Parameters:
  • engine_or_url (str | URL | Engine | AsyncEngine) – a SQLAlchemy URL or engine (preferably asynchronous, but can be synchronous)

  • schema (str | None) – a database schema name to use, if not the default

Note

The data store will not manage the life cycle of any engine instance passed to it, so you need to close the engine afterwards when you’re done with it.

Warning

Do not use SQLite when sharing the data store with multiple schedulers, as there is an unresolved issue with that (#959).

async acquire_jobs(scheduler_id, lease_duration, limit=None)

Acquire unclaimed jobs for execution.

This method claims up to the requested number of jobs for the given scheduler and returns them.

Parameters:
  • scheduler_id (str) – unique identifier of the scheduler

  • lease_duration (timedelta) – the duration of the lease, after which the jobs will be considered to be dead if the scheduler doesn’t extend the lease duration

  • limit (int | None) – maximum number of jobs to claim and return

Return type:

list[Job]

Returns:

the list of claimed jobs

async acquire_schedules(scheduler_id, lease_duration, limit)

Acquire unclaimed due schedules for processing.

This method claims up to the requested number of schedules for the given scheduler and returns them.

For a stored schedule to be eligible for acquisition, it must fulfill one of the following conditions:

  • It is unclaimed (acquired_until is None)

  • Its claim has expired (acquired_until is less than the current datetime)

  • It is claimed by the given scheduler (acquired_by equals scheduler_id)

Parameters:
  • scheduler_id (str) – unique identifier of the scheduler

  • lease_duration (timedelta) – the duration of the lease, after which the schedules can be acquired by another scheduler even if acquired_by is not None

  • limit (int) – maximum number of schedules to claim

Return type:

list[Schedule]

Returns:

the list of claimed schedules

async add_job(job)

Add a job to be executed by an eligible scheduler.

Parameters:

job (Job) – the job object

Return type:

None

async add_schedule(schedule, conflict_policy)

Add or update the given schedule in the data store.

Parameters:
  • schedule (Schedule) – schedule to be added

  • conflict_policy (ConflictPolicy) – policy that determines what to do if there is an existing schedule with the same ID

Return type:

None

async add_task(task)

Add the given task to the store.

If a task with the same ID already exists, it replaces the old one but does NOT affect task accounting (# of running jobs).

Parameters:

task (Task) – the task to be added

Return type:

None

async cleanup()

Perform clean-up operations on the data store.

This method must perform the following operations (in this order):

  • Purge expired job results (where expires_at is less or equal to the current time)

  • Release jobs with expired leases with the cancelled outcome

  • Purge finished schedules (where next_run_time is None) that have no running jobs associated with them

Return type:

None

async extend_acquired_job_leases(scheduler_id, job_ids, duration)

Extend the leases of specified jobs acquired by the given scheduler.

Parameters:
  • scheduler_id (str) – unique identifier of the scheduler

  • job_ids (set[uuid.UUID]) – the identifiers of the jobs the scheduler is running

  • duration (timedelta) – the duration by which to extend the leases

Return type:

None

async extend_acquired_schedule_leases(scheduler_id, schedule_ids, duration)

Extend the leases of specified schedules acquired by the given scheduler.

Parameters:
  • scheduler_id (str) – unique identifier of the scheduler

  • schedule_ids (set[str]) – the identifiers of the schedules the scheduler is currently processing

  • duration (timedelta) – the duration by which to extend the leases

Return type:

None

async get_job_result(job_id)

Retrieve the result of a job.

The result is removed from the store after retrieval.

Parameters:

job_id (uuid.UUID) – the identifier of the job

Return type:

JobResult | None

Returns:

the result, or None if the result was not found

async get_jobs(ids=None)

Get the list of pending jobs.

Parameters:

ids (Iterable[uuid.UUID] | None) – a specific set of job IDs to return, or None to return all jobs

Return type:

list[Job]

Returns:

the list of matching pending jobs, in the order they will be given to schedulers

async get_next_schedule_run_time()

Return the earliest upcoming run time of all the schedules in the store, or None if there are no active schedules.

Return type:

Optional[datetime.datetime]

async get_schedules(ids=None)

Get schedules from the data store.

Parameters:

ids (set[str] | None) – a specific set of schedule IDs to return, or None to return all schedules

Return type:

list[Schedule]

Returns:

the list of matching schedules, in unspecified order

async get_task(task_id)

Get an existing task definition.

Parameters:

task_id (str) – ID of the task to be returned

Return type:

Task

Returns:

the matching task

Raises:

TaskLookupError – if no matching task was found

async get_tasks()

Get all the tasks in this store.

Return type:

list[Task]

Returns:

a list of tasks, sorted by ID

async reap_abandoned_jobs(scheduler_id)

Find jobs marked as acquired by the given scheduler ID and release them with the outcome of abandoned.

Implementers must ensure that the proper JobReleased events are published.

This method is called once during the scheduler startup sequence.

Parameters:

scheduler_id (str) – unique identifier of the scheduler

Return type:

None

async release_job(scheduler_id, job, result)

Release the claim on the given job and record the result.

Parameters:
  • scheduler_id (str) – unique identifier of the scheduler

  • job (Job) – the job to be released

  • result (JobResult) – the result of the job

Return type:

None

async release_schedules(scheduler_id, results)

Release the claims on the given schedules and update them on the store.

The data store is responsible for updating the following fields on stored schedules:

  • last_fire_time

  • next_fire_time

  • trigger

  • acquired_by (must beset to None)

  • acquired_until (must be set to None)

Parameters:
  • scheduler_id (str) – unique identifier of the scheduler

  • results (Sequence[ScheduleResult]) – list of schedule processing results

Return type:

None

async remove_schedules(ids)

Remove schedules from the data store.

Parameters:

ids (Iterable[str]) – a specific set of schedule IDs to remove

Return type:

None

async remove_task(task_id)

Remove the task with the given ID.

Parameters:

task_id (str) – ID of the task to be removed

Raises:

TaskLookupError – if no matching task was found

Return type:

None

async start(exit_stack, event_broker, logger)

Start the event broker.

Parameters:
  • exit_stack (AsyncExitStack) – an asynchronous exit stack which will be processed when the scheduler is shut down

  • event_broker (EventBroker) – the event broker shared between the scheduler, scheduler (if any) and this data store

  • logger (Logger) – the logger object the data store should use to log events

Return type:

None

class apscheduler.datastores.mongodb.MongoDBDataStore(client_or_uri, *, retry_settings=RetrySettings(stop=<tenacity.stop.stop_after_delay object>, wait=<tenacity.wait.wait_exponential object>), serializer=NOTHING, start_from_scratch=False, database='apscheduler')

Uses a MongoDB server to store data.

When started, this data store creates the appropriate indexes on the given database if they’re not already present.

Operations are retried (in accordance to retry_settings) when an operation raises pymongo.errors.ConnectionFailure.

Parameters:
  • client_or_uri (AsyncMongoClient | str) – an asynchronous PyMongo client or a MongoDB connection URI

  • database (str) – name of the database to use

Note

The data store will not manage the life cycle of any client instance passed to it, so you need to close the client after you’re done with it.

Note

Datetimes are stored as integers along with their UTC offsets instead of BSON datetimes due to the BSON datetimes only being accurate to the millisecond while Python datetimes are accurate to the microsecond.

async acquire_jobs(scheduler_id, lease_duration, limit=None)

Acquire unclaimed jobs for execution.

This method claims up to the requested number of jobs for the given scheduler and returns them.

Parameters:
  • scheduler_id (str) – unique identifier of the scheduler

  • lease_duration (timedelta) – the duration of the lease, after which the jobs will be considered to be dead if the scheduler doesn’t extend the lease duration

  • limit (int | None) – maximum number of jobs to claim and return

Return type:

list[Job]

Returns:

the list of claimed jobs

async acquire_schedules(scheduler_id, lease_duration, limit)

Acquire unclaimed due schedules for processing.

This method claims up to the requested number of schedules for the given scheduler and returns them.

For a stored schedule to be eligible for acquisition, it must fulfill one of the following conditions:

  • It is unclaimed (acquired_until is None)

  • Its claim has expired (acquired_until is less than the current datetime)

  • It is claimed by the given scheduler (acquired_by equals scheduler_id)

Parameters:
  • scheduler_id (str) – unique identifier of the scheduler

  • lease_duration (timedelta) – the duration of the lease, after which the schedules can be acquired by another scheduler even if acquired_by is not None

  • limit (int) – maximum number of schedules to claim

Return type:

list[Schedule]

Returns:

the list of claimed schedules

async add_job(job)

Add a job to be executed by an eligible scheduler.

Parameters:

job (Job) – the job object

Return type:

None

async add_schedule(schedule, conflict_policy)

Add or update the given schedule in the data store.

Parameters:
  • schedule (Schedule) – schedule to be added

  • conflict_policy (ConflictPolicy) – policy that determines what to do if there is an existing schedule with the same ID

Return type:

None

async add_task(task)

Add the given task to the store.

If a task with the same ID already exists, it replaces the old one but does NOT affect task accounting (# of running jobs).

Parameters:

task (Task) – the task to be added

Return type:

None

async cleanup()

Perform clean-up operations on the data store.

This method must perform the following operations (in this order):

  • Purge expired job results (where expires_at is less or equal to the current time)

  • Release jobs with expired leases with the cancelled outcome

  • Purge finished schedules (where next_run_time is None) that have no running jobs associated with them

Return type:

None

async extend_acquired_job_leases(scheduler_id, job_ids, duration)

Extend the leases of specified jobs acquired by the given scheduler.

Parameters:
  • scheduler_id (str) – unique identifier of the scheduler

  • job_ids (set[uuid.UUID]) – the identifiers of the jobs the scheduler is running

  • duration (timedelta) – the duration by which to extend the leases

Return type:

None

async extend_acquired_schedule_leases(scheduler_id, schedule_ids, duration)

Extend the leases of specified schedules acquired by the given scheduler.

Parameters:
  • scheduler_id (str) – unique identifier of the scheduler

  • schedule_ids (set[str]) – the identifiers of the schedules the scheduler is currently processing

  • duration (timedelta) – the duration by which to extend the leases

Return type:

None

async get_job_result(job_id)

Retrieve the result of a job.

The result is removed from the store after retrieval.

Parameters:

job_id (uuid.UUID) – the identifier of the job

Return type:

JobResult | None

Returns:

the result, or None if the result was not found

async get_jobs(ids=None)

Get the list of pending jobs.

Parameters:

ids (Iterable[uuid.UUID] | None) – a specific set of job IDs to return, or None to return all jobs

Return type:

list[Job]

Returns:

the list of matching pending jobs, in the order they will be given to schedulers

async get_next_schedule_run_time()

Return the earliest upcoming run time of all the schedules in the store, or None if there are no active schedules.

Return type:

Optional[datetime.datetime]

async get_schedules(ids=None)

Get schedules from the data store.

Parameters:

ids (set[str] | None) – a specific set of schedule IDs to return, or None to return all schedules

Return type:

list[Schedule]

Returns:

the list of matching schedules, in unspecified order

async get_task(task_id)

Get an existing task definition.

Parameters:

task_id (str) – ID of the task to be returned

Return type:

Task

Returns:

the matching task

Raises:

TaskLookupError – if no matching task was found

async get_tasks()

Get all the tasks in this store.

Return type:

list[Task]

Returns:

a list of tasks, sorted by ID

async reap_abandoned_jobs(scheduler_id)

Find jobs marked as acquired by the given scheduler ID and release them with the outcome of abandoned.

Implementers must ensure that the proper JobReleased events are published.

This method is called once during the scheduler startup sequence.

Parameters:

scheduler_id (str) – unique identifier of the scheduler

Return type:

None

async release_job(scheduler_id, job, result)

Release the claim on the given job and record the result.

Parameters:
  • scheduler_id (str) – unique identifier of the scheduler

  • job (Job) – the job to be released

  • result (JobResult) – the result of the job

Return type:

None

async release_schedules(scheduler_id, results)

Release the claims on the given schedules and update them on the store.

The data store is responsible for updating the following fields on stored schedules:

  • last_fire_time

  • next_fire_time

  • trigger

  • acquired_by (must beset to None)

  • acquired_until (must be set to None)

Parameters:
  • scheduler_id (str) – unique identifier of the scheduler

  • results (Sequence[ScheduleResult]) – list of schedule processing results

Return type:

None

async remove_schedules(ids)

Remove schedules from the data store.

Parameters:

ids (Iterable[str]) – a specific set of schedule IDs to remove

Return type:

None

async remove_task(task_id)

Remove the task with the given ID.

Parameters:

task_id (str) – ID of the task to be removed

Raises:

TaskLookupError – if no matching task was found

Return type:

None

async start(exit_stack, event_broker, logger)

Start the event broker.

Parameters:
  • exit_stack (AsyncExitStack) – an asynchronous exit stack which will be processed when the scheduler is shut down

  • event_broker (EventBroker) – the event broker shared between the scheduler, scheduler (if any) and this data store

  • logger (Logger) – the logger object the data store should use to log events

Return type:

None

Event brokers

class apscheduler.abc.EventBroker

Interface for objects that can be used to publish notifications to interested subscribers.

abstractmethod async publish(event)

Publish an event.

Return type:

None

abstractmethod async publish_local(event)

Publish an event, but only to local subscribers.

Return type:

None

abstractmethod async start(exit_stack, logger)

Start the event broker.

Parameters:
  • exit_stack (AsyncExitStack) – an asynchronous exit stack which will be processed when the scheduler is shut down

  • logger (Logger) – the logger object the event broker should use to log events

Return type:

None

abstractmethod subscribe(callback, event_types=None, *, is_async=True, one_shot=False)

Subscribe to events from this event broker.

Parameters:
  • callback (Callable[[TypeVar(T_Event, bound= Event)], Any]) – callable to be called with the event object when an event is published

  • event_types (Iterable[type[TypeVar(T_Event, bound= Event)]] | None) – an iterable of concrete Event classes to subscribe to

  • is_async (bool) – True if the (synchronous) callback should be called on the event loop thread, False if it should be called in a scheduler thread. If the callback is a coroutine function, this flag is ignored.

  • one_shot (bool) – if True, automatically unsubscribe after the first matching event

Return type:

Subscription

class apscheduler.abc.Subscription

Represents a subscription with an event source.

If used as a context manager, unsubscribes on exit.

abstractmethod unsubscribe()

Cancel this subscription.

Does nothing if the subscription has already been cancelled.

Return type:

None

class apscheduler.eventbrokers.local.LocalEventBroker

Asynchronous, local event broker.

This event broker only broadcasts within the process it runs in, and is therefore not suitable for multi-node or multiprocess use cases.

Does not serialize events.

async publish(event)

Publish an event.

Return type:

None

class apscheduler.eventbrokers.asyncpg.AsyncpgEventBroker(dsn, options=NOTHING, *, retry_settings=RetrySettings(stop=<tenacity.stop.stop_after_delay object>, wait=<tenacity.wait.wait_exponential object>), serializer=NOTHING, channel='apscheduler', max_idle_time=10)

An asynchronous, asyncpg based event broker that uses a PostgreSQL server to broadcast events using its NOTIFY mechanism.

Parameters:
  • dsn (str) – a libpq connection string (e.g. postgres://user:pass@host:port/dbname)

  • options (Mapping[str, Any]) – extra keyword arguments passed to asyncpg.connection.connect()

  • channel (str) – the NOTIFY channel to use

  • max_idle_time (float) – maximum time to let the connection go idle, before sending a SELECT 1 query to prevent a connection timeout

classmethod from_async_sqla_engine(engine, options=None, **kwargs)

Create a new asyncpg event broker from an SQLAlchemy engine.

The engine will only be used to create the appropriate options for asyncpg.connection.connect().

Parameters:
  • engine (sqlalchemy.ext.asyncio.AsyncEngine) – an asynchronous SQLAlchemy engine using asyncpg as the driver

  • options (Mapping[str, Any] | None) – extra keyword arguments passed to asyncpg.connection.connect()

  • kwargs (Any) – keyword arguments to pass to the initializer of this class

Return type:

AsyncpgEventBroker

Returns:

the newly created event broker

async publish(event)

Publish an event.

Return type:

None

async start(exit_stack, logger)

Start the event broker.

Parameters:
  • exit_stack (AsyncExitStack) – an asynchronous exit stack which will be processed when the scheduler is shut down

  • logger (Logger) – the logger object the event broker should use to log events

Return type:

None

class apscheduler.eventbrokers.psycopg.PsycopgEventBroker(conninfo, options=NOTHING, *, retry_settings=RetrySettings(stop=<tenacity.stop.stop_after_delay object>, wait=<tenacity.wait.wait_exponential object>), serializer=NOTHING, channel='apscheduler', max_idle_time=10)

An asynchronous, psycopg based event broker that uses a PostgreSQL server to broadcast events using its NOTIFY mechanism.

Parameters:
  • conninfo (str) – a libpq connection string (e.g. postgres://user:pass@host:port/dbname)

  • options (Mapping[str, Any]) – extra keyword arguments passed to psycopg.AsyncConnection.connect()

  • channel (str) – the NOTIFY channel to use

  • max_idle_time (float) – maximum time (in seconds) to let the connection go idle, before sending a SELECT 1 query to prevent a connection timeout

classmethod from_async_sqla_engine(engine, options=None, **kwargs)

Create a new psycopg event broker from a SQLAlchemy engine.

The engine will only be used to create the appropriate options for psycopg.AsyncConnection.connect().

Parameters:
  • engine (sqlalchemy.ext.asyncio.AsyncEngine) – an asynchronous SQLAlchemy engine using psycopg as the driver

  • options (Mapping[str, Any] | None) – extra keyword arguments passed to psycopg.AsyncConnection.connect()

  • kwargs (Any) – keyword arguments to pass to the initializer of this class

Return type:

PsycopgEventBroker

Returns:

the newly created event broker

async publish(event)

Publish an event.

Return type:

None

async start(exit_stack, logger)

Start the event broker.

Parameters:
  • exit_stack (AsyncExitStack) – an asynchronous exit stack which will be processed when the scheduler is shut down

  • logger (Logger) – the logger object the event broker should use to log events

Return type:

None

class apscheduler.eventbrokers.mqtt.MQTTEventBroker(host='localhost', port=None, transport='tcp', client_id=None, ssl=False, *, retry_settings=RetrySettings(stop=<tenacity.stop.stop_after_delay object>, wait=<tenacity.wait.wait_exponential object>), serializer=NOTHING, topic='apscheduler', subscribe_qos=0, publish_qos=0)

An event broker that uses an MQTT (v3.1 or v5) broker to broadcast events.

Requires the paho-mqtt library (v2.0 or later) to be installed.

Parameters:
  • host (str) – MQTT broker host (or UNIX socket path)

  • port (int | None) – MQTT broker port (for tcp or websocket transports)

  • transport (str) – one of tcp, websocket or unix (default: tcp)

  • client_id (str | None) – MQTT client ID (needed to resume an MQTT session if a connection is broken)

  • ssl (bool | SSLContext) – either True or a custom SSL context to enable SSL/TLS, False to disable

  • topic (str) – topic on which to send the messages

  • subscribe_qos (int) – MQTT QoS to use for subscribing messages

  • publish_qos (int) – MQTT QoS to use for publishing messages

async publish(event)

Publish an event.

Return type:

None

async start(exit_stack, logger)

Start the event broker.

Parameters:
  • exit_stack (AsyncExitStack) – an asynchronous exit stack which will be processed when the scheduler is shut down

  • logger (Logger) – the logger object the event broker should use to log events

Return type:

None

class apscheduler.eventbrokers.redis.RedisEventBroker(client_or_url, *, retry_settings=RetrySettings(stop=<tenacity.stop.stop_after_delay object>, wait=<tenacity.wait.wait_exponential object>), serializer=NOTHING, channel='apscheduler', stop_check_interval=1)

An event broker that uses a Redis server to broadcast events.

Requires the redis library to be installed.

Parameters:
  • client_or_url (Redis | str) – an asynchronous Redis client or a Redis URL (`redis://...`)

  • channel (str) – channel on which to send the messages

  • stop_check_interval (float) – interval (in seconds) on which the channel listener should check if it should stop (higher values mean slower reaction time but less CPU use)

Note

The event broker will not manage the life cycle of any client instance passed to it, so you need to close the client afterwards when you’re done with it.

async publish(event)

Publish an event.

Return type:

None

async start(exit_stack, logger)

Start the event broker.

Parameters:
  • exit_stack (AsyncExitStack) – an asynchronous exit stack which will be processed when the scheduler is shut down

  • logger (Logger) – the logger object the event broker should use to log events

Return type:

None

Serializers

class apscheduler.abc.Serializer

Interface for classes that implement (de)serialization.

abstractmethod deserialize(serialized)

Restore a previously serialized object from bytestring

Parameters:

serialized (bytes) – a bytestring previously received from serialize()

Return type:

Any

Returns:

a copy of the original object

abstractmethod serialize(obj)

Turn the given object into a bytestring.

Must handle the serialization of at least any JSON type, plus the following:

Return type:

bytes

Returns:

a bytestring that can be later restored using deserialize()

class apscheduler.serializers.cbor.CBORSerializer(*, type_tag=4664, dump_options=NOTHING, load_options=NOTHING)

Serializes objects using CBOR (RFC 8949).

Can serialize types not normally CBOR serializable, if they implement __getstate__() and __setstate__().

Parameters:
deserialize(serialized)

Restore a previously serialized object from bytestring

Parameters:

serialized (bytes) – a bytestring previously received from serialize()

Returns:

a copy of the original object

serialize(obj)

Turn the given object into a bytestring.

Must handle the serialization of at least any JSON type, plus the following:

Return type:

bytes

Returns:

a bytestring that can be later restored using deserialize()

class apscheduler.serializers.json.JSONSerializer(*, magic_key='_apscheduler_json', dump_options=NOTHING, load_options=NOTHING)

Serializes objects using JSON.

Can serialize types not normally CBOR serializable, if they implement __getstate__() and __setstate__(). These objects are serialized into dicts that contain the necessary information for deserialization in magic_key.

Parameters:
  • magic_key (str) – name of a specially handled dict key that indicates that a dict contains a serialized instance of an arbitrary type

  • dump_options (dict[str, Any]) – keyword arguments passed to json.dumps()

  • load_options (dict[str, Any]) – keyword arguments passed to json.loads()

deserialize(serialized)

Restore a previously serialized object from bytestring

Parameters:

serialized (bytes) – a bytestring previously received from serialize()

Returns:

a copy of the original object

serialize(obj)

Turn the given object into a bytestring.

Must handle the serialization of at least any JSON type, plus the following:

Return type:

bytes

Returns:

a bytestring that can be later restored using deserialize()

class apscheduler.serializers.pickle.PickleSerializer(*, protocol=4)

Uses the pickle module to (de)serialize objects.

As this serialization method is native to Python, it is able to serialize a wide range of types, at the expense of being insecure. Do not use this serializer unless you can fully trust the entire system to not have maliciously injected data. Such data can be made to call arbitrary functions with arbitrary arguments on unpickling.

Parameters:

protocol (int) – the pickle protocol number to use

deserialize(serialized)

Restore a previously serialized object from bytestring

Parameters:

serialized (bytes) – a bytestring previously received from serialize()

Returns:

a copy of the original object

serialize(obj)

Turn the given object into a bytestring.

Must handle the serialization of at least any JSON type, plus the following:

Return type:

bytes

Returns:

a bytestring that can be later restored using deserialize()

Triggers

class apscheduler.abc.Trigger

Abstract base class that defines the interface that every trigger must implement.

abstractmethod __getstate__()

Return the serializable state of the trigger.

Return type:

Any

abstractmethod __setstate__(state)

Initialize an empty instance from an existing state.

Return type:

None

abstractmethod next()

Return the next datetime to fire on.

If no such datetime can be calculated, None is returned.

Raises:

MaxIterationsReached – if the trigger’s internal logic has exceeded a set maximum of iterations (used to detect potentially infinite loops)

Return type:

Optional[datetime.datetime]

class apscheduler.triggers.date.DateTrigger(run_time)

Triggers once on the given date/time.

Parameters:

run_time (Union[datetime.datetime, str]) – the date/time to run the job at

next()

Return the next datetime to fire on.

If no such datetime can be calculated, None is returned.

Raises:

MaxIterationsReached – if the trigger’s internal logic has exceeded a set maximum of iterations (used to detect potentially infinite loops)

Return type:

Optional[datetime.datetime]

class apscheduler.triggers.interval.IntervalTrigger(*, weeks=0, days=0, hours=0, minutes=0, seconds=0, microseconds=0, start_time=NOTHING, end_time=None)

Triggers on specified intervals.

The first trigger time is on start_time which is the moment the trigger was created unless specifically overridden. If end_time is specified, the last trigger time will be at or before that time. If no end_time has been given, the trigger will produce new trigger times as long as the resulting datetimes are valid datetimes in Python.

Parameters:
  • weeks (float) – number of weeks to wait

  • days (float) – number of days to wait

  • hours (float) – number of hours to wait

  • minutes (float) – number of minutes to wait

  • seconds (float) – number of seconds to wait

  • microseconds (float) – number of microseconds to wait

  • start_time (Union[datetime.datetime, str]) – first trigger date/time (defaults to current date/time if omitted)

  • end_time (Union[datetime.datetime, str]) – latest possible date/time to trigger on

next()

Return the next datetime to fire on.

If no such datetime can be calculated, None is returned.

Raises:

MaxIterationsReached – if the trigger’s internal logic has exceeded a set maximum of iterations (used to detect potentially infinite loops)

Return type:

Optional[datetime.datetime]

class apscheduler.triggers.calendarinterval.CalendarIntervalTrigger(*, years=0, months=0, weeks=0, days=0, hour=0, minute=0, second=0, start_date=NOTHING, end_date=None, timezone='local')

Runs the task on specified calendar-based intervals always at the same exact time of day.

When calculating the next date, the years and months parameters are first added to the previous date while keeping the day of the month constant. This is repeated until the resulting date is valid. After that, the weeks and days parameters are added to that date. Finally, the date is combined with the given time (hour, minute, second) to form the final datetime.

This means that if the days or weeks parameters are not used, the task will always be executed on the same day of the month at the same wall clock time, assuming the date and time are valid.

If the resulting datetime is invalid due to a daylight saving forward shift, the date is discarded and the process moves on to the next date. If instead the datetime is ambiguous due to a backward DST shift, the earlier of the two resulting datetimes is used.

If no previous run time is specified when requesting a new run time (like when starting for the first time or resuming after being paused), start_date is used as a reference and the next valid datetime equal to or later than the current time will be returned. Otherwise, the next valid datetime starting from the previous run time is returned, even if it’s in the past.

Warning

Be wary of setting a start date near the end of the month (29. – 31.) if you have months specified in your interval, as this will skip the months when those days do not exist. Likewise, setting the start date on the leap day (February 29th) and having years defined may cause some years to be skipped.

Users are also discouraged from using a time inside the target timezone’s DST switching period (typically around 2 am) since a date could either be skipped or repeated due to the specified wall clock time either occurring twice or not at all.

Parameters:
  • years (int) – number of years to wait

  • months (int) – number of months to wait

  • weeks (int) – number of weeks to wait

  • days (int) – number of days to wait

  • hour (int) – hour to run the task at

  • minute (int) – minute to run the task at

  • second (int) – second to run the task at

  • start_date (date | str) – first date to trigger on (defaults to current date if omitted)

  • end_date (date | str) – latest possible date to trigger on

  • timezone (tzinfo | str) – time zone to use for calculating the next fire time

next()

Return the next datetime to fire on.

If no such datetime can be calculated, None is returned.

Raises:

MaxIterationsReached – if the trigger’s internal logic has exceeded a set maximum of iterations (used to detect potentially infinite loops)

Return type:

Optional[datetime.datetime]

class apscheduler.triggers.combining.AndTrigger(triggers, threshold=1, max_iterations=10000)

Fires on times produced by the enclosed triggers whenever the fire times are within the given threshold.

If the produced fire times are not within the given threshold of each other, the trigger(s) that produced the earliest fire time will be asked for their next fire time and the iteration is restarted. If instead all the triggers agree on a fire time, all the triggers are asked for their next fire times and the earliest of the previously produced fire times will be returned.

This trigger will be finished when any of the enclosed trigger has finished.

Parameters:
  • triggers (list[Trigger]) – triggers to combine

  • threshold (timedelta | int) – maximum time difference between the next fire times of the triggers in order for the earliest of them to be returned from next() (in seconds, or as timedelta)

  • max_iterations (int | None) – maximum number of iterations of fire time calculations before giving up

next()

Return the next datetime to fire on.

If no such datetime can be calculated, None is returned.

Raises:

MaxIterationsReached – if the trigger’s internal logic has exceeded a set maximum of iterations (used to detect potentially infinite loops)

Return type:

Optional[datetime.datetime]

class apscheduler.triggers.combining.OrTrigger(triggers)

Fires on every fire time of every trigger in chronological order. If two or more triggers produce the same fire time, it will only be used once.

This trigger will be finished when none of the enclosed triggers can produce any new fire times.

Parameters:

triggers (list[Trigger]) – triggers to combine

next()

Return the next datetime to fire on.

If no such datetime can be calculated, None is returned.

Raises:

MaxIterationsReached – if the trigger’s internal logic has exceeded a set maximum of iterations (used to detect potentially infinite loops)

Return type:

Optional[datetime.datetime]

class apscheduler.triggers.cron.CronTrigger(*, year=None, month=None, day=None, week=None, day_of_week=None, hour=None, minute=None, second=None, start_time=NOTHING, end_time=None, timezone=NOTHING)

Triggers when current time matches all specified time constraints, similarly to how the UNIX cron scheduler works.

Parameters:
  • year (int | str | None) – 4-digit year

  • month (int | str | None) – month (1-12)

  • day (int | str | None) – day of the (1-31)

  • week (int | str | None) – ISO week (1-53)

  • day_of_week (int | str | None) – number or name of weekday (0-7 or sun,mon,tue,wed,thu,fri,sat, sun)

  • hour (int | str | None) – hour (0-23)

  • minute (int | str | None) – minute (0-59)

  • second (int | str | None) – second (0-59)

  • start_time (Union[datetime.datetime, str]) – earliest possible date/time to trigger on (defaults to current time)

  • end_time (Union[datetime.datetime, str]) – latest possible date/time to trigger on

  • timezone (tzinfo | str) – time zone to use for the date/time calculations (defaults to the local timezone)

Note

The first weekday is always monday.

classmethod from_crontab(expr, *, start_time=None, end_time=None, timezone='local')

Create a CronTrigger from a standard crontab expression.

See https://en.wikipedia.org/wiki/Cron for more information on the format accepted here.

Parameters:
  • expr (str) – minute, hour, day of month, month, day of week

  • start_time (Optional[datetime.datetime]) – earliest possible date/time to trigger on (defaults to current time)

  • end_time (Optional[datetime.datetime]) – latest possible date/time to trigger on

  • timezone (tzinfo | str) – time zone to use for the date/time calculations (defaults to local timezone if omitted)

Return type:

CronTrigger

next()

Return the next datetime to fire on.

If no such datetime can be calculated, None is returned.

Raises:

MaxIterationsReached – if the trigger’s internal logic has exceeded a set maximum of iterations (used to detect potentially infinite loops)

Return type:

Optional[datetime.datetime]

Events

class apscheduler.Event(*, timestamp=NOTHING)

Base class for all events.

Variables:

timestamp – the time when the event occurred

class apscheduler.DataStoreEvent(*, timestamp=NOTHING)

Base class for events originating from a data store.

class apscheduler.TaskAdded(*, timestamp=NOTHING, task_id)

Signals that a new task was added to the store.

Variables:

task_id – ID of the task that was added

class apscheduler.TaskUpdated(*, timestamp=NOTHING, task_id)

Signals that a task was updated in a data store.

Variables:

task_id – ID of the task that was updated

class apscheduler.TaskRemoved(*, timestamp=NOTHING, task_id)

Signals that a task was removed from the store.

Variables:

task_id – ID of the task that was removed

class apscheduler.ScheduleAdded(*, timestamp=NOTHING, schedule_id, task_id, next_fire_time)

Signals that a new schedule was added to the store.

Variables:
  • schedule_id – ID of the schedule that was added

  • task_id – ID of the task the schedule belongs to

  • next_fire_time – the first run time calculated for the schedule

class apscheduler.ScheduleUpdated(*, timestamp=NOTHING, schedule_id, task_id, next_fire_time)

Signals that a schedule has been updated in the store.

Variables:
  • schedule_id – ID of the schedule that was updated

  • task_id – ID of the task the schedule belongs to

  • next_fire_time – the next time the schedule will run

class apscheduler.ScheduleRemoved(*, timestamp=NOTHING, schedule_id, task_id, finished)

Signals that a schedule was removed from the store.

Variables:
  • schedule_id – ID of the schedule that was removed

  • task_id – ID of the task the schedule belongs to

  • finishedTrue if the schedule was removed automatically because its trigger had no more fire times left

class apscheduler.JobAdded(*, timestamp=NOTHING, job_id, task_id, schedule_id)

Signals that a new job was added to the store.

Variables:
  • job_id – ID of the job that was added

  • task_id – ID of the task the job would run

  • schedule_id – ID of the schedule the job was created from

class apscheduler.JobRemoved(*, timestamp=NOTHING, job_id, task_id)

Signals that a job was removed from the store.

Variables:
  • job_id – ID of the job that was removed

  • task_id – ID of the task the job would have run

class apscheduler.ScheduleDeserializationFailed(*, timestamp=NOTHING, schedule_id, exception)

Signals that the deserialization of a schedule has failed.

Variables:
  • schedule_id – ID of the schedule that failed to deserialize

  • exception – the exception that was raised during deserialization

class apscheduler.JobDeserializationFailed(*, timestamp=NOTHING, job_id, exception)

Signals that the deserialization of a job has failed.

Variables:
  • job_id – ID of the job that failed to deserialize

  • exception – the exception that was raised during deserialization

class apscheduler.SchedulerEvent(*, timestamp=NOTHING)

Base class for events originating from a scheduler.

class apscheduler.SchedulerStarted(*, timestamp=NOTHING)
class apscheduler.SchedulerStopped(*, timestamp=NOTHING, exception=None)

Signals that a scheduler has stopped.

Variables:

exception – the exception that caused the scheduler to stop, if any

class apscheduler.JobAcquired(*, timestamp=NOTHING, job_id, scheduler_id, task_id, schedule_id=None, scheduled_start)

Signals that a scheduler has acquired a job for processing.

Parameters:
  • job_id (Union[uuid.UUID, str]) – the ID of the job that was acquired

  • scheduler_id (str) – the ID of the scheduler that acquired the job

  • task_id (str) – ID of the task the job belongs to

  • schedule_id (str | None) – ID of the schedule that

  • scheduled_start (Union[datetime.datetime, str]) – the time the job was scheduled to start via a schedule (if any)

classmethod from_job(job, scheduler_id)

Create a new job-acquired event from a job and a scheduler ID.

Parameters:
  • job (Job) – the job that was acquired

  • scheduler_id (str) – the ID of the scheduler that acquired the job

Return type:

JobAcquired

Returns:

a new job-acquired event

class apscheduler.JobReleased(*, timestamp=NOTHING, job_id, scheduler_id, task_id, schedule_id=None, scheduled_start, started_at, outcome, exception_type=None, exception_message=None, exception_traceback=None)

Signals that a scheduler has finished processing of a job.

Parameters:
  • job_id (Union[uuid.UUID, str]) – the ID of the job that was released

  • scheduler_id (str) – the ID of the scheduler that released the job

  • task_id (str) – ID of the task run by the job

  • schedule_id (str | None) – ID of the schedule (if any) that created the job

  • scheduled_start (Union[datetime.datetime, str]) – the time the job was scheduled to start via the schedule (if any)

  • started_at (Union[datetime.datetime, str]) – the time the executor actually started running the job (None if the job was skipped due to missing its start deadline)

  • outcome (Any) – the outcome of the job

  • exception_type (str | None) – the fully qualified name of the exception if outcome is JobOutcome.error

  • exception_message (str | None) – the result of str(exception) if outcome is JobOutcome.error

  • exception_traceback (list[str] | None) – the traceback lines from the exception if outcome is JobOutcome.error

classmethod from_result(result, scheduler_id, task_id, schedule_id, scheduled_fire_time=None)

Create a new job-released event from a job, the job result and a scheduler ID.

Parameters:
  • result (JobResult) – the result of the job

  • scheduler_id (str) – the ID of the scheduler that acquired the job

  • task_id (str) – the job’s task ID

  • schedule_id (str | None) – ID of the schedule (if any) from which the job was spawned

  • scheduled_fire_time (Optional[datetime.datetime]) – the time the job was scheduled to start (if the job was spawned from a schedule)

Return type:

JobReleased

Returns:

a new job-released event

Enumerated types

class apscheduler.SchedulerRole

Bases: Enum

Specifies what the scheduler should be doing when it’s running.

scheduler

processes due schedules, but won’t run jobs

worker

runs due jobs, but won’t process schedules

both

processes schedules and runs due jobs

class apscheduler.RunState

Bases: Enum

Used to track the running state of schedulers.

starting

not running yet, but in the process of starting

started

running

stopping

still running but in the process of shutting down

stopped

not running

class apscheduler.JobOutcome

Bases: Enum

Used to indicate how the execution of a job ended.

success

the job completed successfully

error

the job raised an exception

missed_start_deadline

the job’s execution was delayed enough for it to miss its start deadline (scheduled time + misfire grace time)

deserialization_failed

the deserialization operation failed

cancelled

the job’s execution was cancelled

abandoned

the worker running the job stopped unexpectedly and the job was never marked as done

class apscheduler.ConflictPolicy

Bases: Enum

Used to indicate what to do when trying to add a schedule whose ID conflicts with an existing schedule.

replace

replace the existing schedule with a new one

do_nothing

keep the existing schedule as-is and drop the new schedule

exception

raise an exception if a conflict is detected

class apscheduler.CoalescePolicy

Bases: Enum

Used to indicate how to queue jobs for a schedule that has accumulated multiple run times since the last scheduler iteration.

earliest

run once, with the earliest fire time

latest

run once, with the latest fire time

all

submit one job for every accumulated fire time

Context variables

See the contextvars module for information on how to work with context variables.

apscheduler.current_scheduler: ContextVar[Scheduler]

The current scheduler.

apscheduler.current_async_scheduler: ContextVar[AsyncScheduler]

The current asynchronous scheduler.

apscheduler.current_job: ContextVar[Job]

The job being currently run (available when running the job’s target callable).

Exceptions

exception apscheduler.TaskLookupError(task_id)

Raised by a data store when it cannot find the requested task.

exception apscheduler.ScheduleLookupError(schedule_id)

Raised by a scheduler when it cannot find the requested schedule.

exception apscheduler.JobLookupError(job_id)

Raised when the job store cannot find a job for update or removal.

exception apscheduler.CallableLookupError

Raised when the target callable for a job could not be found.

exception apscheduler.JobResultNotReady(job_id)

Raised by get_job_result() if the job result is not ready.

exception apscheduler.JobCancelled

Raised by get_job_result() if the job was cancelled.

exception apscheduler.JobDeadlineMissed

Raised by get_job_result() if the job failed to start within the allotted time.

exception apscheduler.ConflictingIdError(schedule_id)

Raised when trying to add a schedule to a store that already contains a schedule by that ID, and the conflict policy of exception is used.

exception apscheduler.SerializationError

Raised when a serializer fails to serialize the given object.

exception apscheduler.DeserializationError

Raised when a serializer fails to deserialize the given object.

exception apscheduler.MaxIterationsReached

Raised when a trigger has reached its maximum number of allowed computation iterations when trying to calculate the next fire time.

Support classes for retrying failures

class apscheduler.RetrySettings(*, stop=<tenacity.stop.stop_after_delay object>, wait=<tenacity.wait.wait_exponential object>)

Settings for retrying an operation with Tenacity.

Parameters:
  • stop (stop_base) – defines when to stop trying

  • wait (wait_base) – defines how long to wait between attempts

class apscheduler.RetryMixin(*, retry_settings=RetrySettings(stop=<tenacity.stop.stop_after_delay object>, wait=<tenacity.wait.wait_exponential object>))

Mixin that provides support for retrying operations.

Parameters:

retry_settings (apscheduler.RetrySettings) – Tenacity settings for retrying operations in case of a database connecitivty problem

Support classes for unset options

apscheduler.unset

Sentinel value for unset option values.

class apscheduler.UnsetValue

The type of unset.