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 taskmax_running_jobs (
int|None|UnsetValue) – maximum number of instances of this task that are allowed to run concurrentlymisfire_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
- 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 (
Noneif 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:
id (
str|UnsetValue) – the task ID to usejob_executor (
str|UnsetValue) – name of the job executor that will run the taskmax_running_jobs (
int|None|UnsetValue) – maximum number of instances of the task that are allowed to run concurrentlymisfire_grace_time (
int|timedelta|None|UnsetValue) – maximum number of seconds the run time of jobs created for the task are allowed to be late, compared to the scheduled run timemetadata (
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
- 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
AsyncSchedulerclass 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 withkwargs (
Mapping[str,Any] |None) – keyword arguments to call the target callable withjob_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 informationresult_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 definitiontrigger (
Trigger) – determines the times when the task should be runid (
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 functionkwargs (
Mapping[str,Any] |None) – keyword arguments to be passed to the task functionpaused (
bool) – whether the schedule is pausedjob_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 processingmisfire_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 timemetadata (
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 informationmax_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 schedulejob_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 scheduleconflict_policy (
ConflictPolicy) – determines what to do if a schedule with the same ID already exists in the data store
- Return type:
- Returns:
the ID of the newly added schedule
- 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 ofdefault_job_executorscheduler attributemisfire_grace_time:Nonemax_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:
func_or_task_id (
Task|str|Callable[...,Any]) – either a task, task ID or a callablefunc (
Callable[...,Any] |UnsetValue) – a callable that will be associated with the task (can be omitted if the callable is already passed asfunc_or_task_id)job_executor (
str|UnsetValue) – name of the job executor to run the task withmisfire_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 timemax_running_jobs (
int|None|UnsetValue) – maximum number of instances of the task that are allowed to run concurrentlymetadata (
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
- Raises:
TypeError – if
func_or_task_idis neither a task, task ID or a callable- Return type:
- 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) – ifTrue, wait until the job has ended (one way or another),Falseto raise an exception if the result is not yet available
- Return type:
- Returns:
the job result, or
Noneif the job finished but didn’t record a result (result_expiration_timewas 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=Falseis set
- 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.
- 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:
- get_schedules()
Retrieve all schedules from the data store.
- get_tasks()
Retrieve all currently defined tasks.
- remove_schedule(id)
Remove the given schedule from the data store.
- 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:
func_or_task_id (
str|Callable[...,Any]) – either a callable or an ID of an existing task definitionargs (
Iterable[Any] |None) – positional arguments to be passed to the task functionkwargs (
Mapping[str,Any] |None) – keyword arguments to be passed to the task functionjob_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
- Return type:
- Returns:
the return value of the task function
- start_in_background()
Launch the scheduler in a new thread.
This method registers
atexithooks to shut down the scheduler and wait for the thread to finish.- Raises:
RuntimeError – if the scheduler is not in the
stoppedstate- Return type:
- 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:
- 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 publishedevent_types (
type[TypeVar(T_Event, bound= Event)] |Iterable[type[TypeVar(T_Event, bound= Event)]] |None) – an iterable of concrete Event classes to subscribe toone_shot (
bool) – ifTrue, automatically unsubscribe after the first matching event
- unpause_schedule(id, *, resume_from=None)
Unpause the specified schedule.
- wait_until_stopped()
Wait until the scheduler is in the
stoppedorstoppingstate.If the scheduler is already stopped or in the process of stopping, this method returns immediately. Otherwise, it waits until the scheduler posts the
SchedulerStoppedevent.- Return type:
- 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
asyncioor 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 jobsevent_broker (
EventBroker) – the event broker to use for publishing an subscribing eventsidentity (
str) – the unique identifier of the schedulerrole (
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 oncejob_executors (
MutableMapping[str,JobExecutor]) – a mutable mapping of executor names to executor instancestask_defaults (
TaskDefaults) – default settings for newly configured taskscleanup_interval (
timedelta|int) – interval (as seconds or timedelta) between automatic calls tocleanup()–Noneto disable automatic clean-uplease_duration (
timedelta|int) – maximum amount of time (as seconds or timedelta) that the scheduler can keep a lock on a schedule or tasklogger (
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 withkwargs (
Mapping[str,Any] |None) – keyword arguments to call the target callable withjob_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 informationresult_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 definitiontrigger (
Trigger) – determines the times when the task should be runid (
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 functionkwargs (
Mapping[str,Any] |None) – keyword arguments to be passed to the task functionpaused (
bool) – whether the schedule is pausedjob_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 processingmisfire_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 timemetadata (
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 informationmax_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 schedulejob_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 scheduleconflict_policy (
ConflictPolicy) – determines what to do if a schedule with the same ID already exists in the data store
- Return type:
- Returns:
the ID of the newly added schedule
- 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 ofdefault_job_executorscheduler attributemisfire_grace_time:Nonemax_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:
func_or_task_id (
Task|str|Callable[...,Any]) – either a task, task ID or a callablefunc (
Callable[...,Any] |UnsetValue) – a callable that will be associated with the task (can be omitted if the callable is already passed asfunc_or_task_id)job_executor (
str|UnsetValue) – name of the job executor to run the task withmisfire_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 timemax_running_jobs (
int|None|UnsetValue) – maximum number of instances of the task that are allowed to run concurrentlymetadata (
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
- Raises:
TypeError – if
func_or_task_idis neither a task, task ID or a callable- Return type:
- 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) – ifTrue, wait until the job has ended (one way or another),Falseto raise an exception if the result is not yet available
- Return type:
- Returns:
the job result, or
Noneif the job finished but didn’t record a result (result_expiration_timewas 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=Falseis set
- 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.
- 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:
- async get_schedules()
Retrieve all schedules from the data store.
- async get_tasks()
Retrieve all currently defined tasks.
- async remove_schedule(id)
Remove the given schedule from the data store.
- 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:
func_or_task_id (
str|Callable[...,Any]) – either a callable or an ID of an existing task definitionargs (
Iterable[Any] |None) – positional arguments to be passed to the task functionkwargs (
Mapping[str,Any] |None) – keyword arguments to be passed to the task functionjob_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
- Return type:
- 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:
- 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:
- 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 publishedevent_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 toone_shot (
bool) – ifTrue, automatically unsubscribe after the first matching eventis_async (
bool) –Trueif the (synchronous) callback should be called on the event loop thread,Falseif it should be called in a worker thread. Ifcallbackis a coroutine function, this flag is ignored.
- async unpause_schedule(id, *, resume_from=None)
Unpause the specified schedule.
- async wait_until_stopped()
Wait until the scheduler is in the
stoppedorstoppingstate.If the scheduler is already stopped or in the process of stopping, this method returns immediately. Otherwise, it waits until the scheduler posts the
SchedulerStoppedevent.- Return type:
Job executors
- class apscheduler.abc.JobExecutor
- abstractmethod async run_job(func, job)
Run the given job by calling the given function.
- 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:
- 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.
- 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.
- 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:
- class apscheduler.executors.qt.QtJobExecutor
- async run_job(func, job)
Run the given job by calling the given function.
- 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:
- 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.
- 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:
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:
- Return type:
- 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_untilisNone)Its claim has expired (
acquired_untilis less than the current datetime)It is claimed by the given scheduler (
acquired_byequalsscheduler_id)
- Parameters:
- Return type:
- Returns:
the list of claimed schedules
- abstractmethod async add_job(job)
Add a job to be executed by an eligible scheduler.
- abstractmethod async add_schedule(schedule, conflict_policy)
Add or update the given schedule in the data store.
- Parameters:
schedule (
Schedule) – schedule to be addedconflict_policy (
ConflictPolicy) – policy that determines what to do if there is an existing schedule with the same ID
- Return type:
- 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).
- 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_atis less or equal to the current time)Release jobs with expired leases with the
cancelledoutcomePurge finished schedules (where
next_run_timeisNone) that have no running jobs associated with them
- Return type:
- abstractmethod async extend_acquired_job_leases(scheduler_id, job_ids, duration)
Extend the leases of specified jobs acquired by the given scheduler.
- abstractmethod async extend_acquired_schedule_leases(scheduler_id, schedule_ids, duration)
Extend the leases of specified schedules acquired by the given scheduler.
- abstractmethod async get_job_result(job_id)
Retrieve the result of a job.
The result is removed from the store after retrieval.
- abstractmethod async get_jobs(ids=None)
Get the list of pending jobs.
- abstractmethod async get_next_schedule_run_time()
Return the earliest upcoming run time of all the schedules in the store, or
Noneif there are no active schedules.- Return type:
Optional[datetime.datetime]
- abstractmethod async get_schedules(ids=None)
Get schedules from the data store.
- abstractmethod async get_task(task_id)
Get an existing task definition.
- Parameters:
task_id (
str) – ID of the task to be returned- Return type:
- Returns:
the matching task
- Raises:
TaskLookupError – if no matching task was found
- abstractmethod async get_tasks()
Get all the tasks in this store.
- 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
JobReleasedevents are published.This method is called once during the scheduler startup sequence.
- abstractmethod async release_job(scheduler_id, job, result)
Release the claim on the given job and record the result.
- 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_timenext_fire_timetriggeracquired_by(must beset toNone)acquired_until(must be set toNone)
- Parameters:
scheduler_id (
str) – unique identifier of the schedulerresults (
Sequence[ScheduleResult]) – list of schedule processing results
- Return type:
- abstractmethod async remove_schedules(ids)
Remove schedules from the data store.
- 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:
- 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 downevent_broker (
EventBroker) – the event broker shared between the scheduler, scheduler (if any) and this data storelogger (
Logger) – the logger object the data store should use to log events
- Return type:
- 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:
- Return type:
- 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_untilisNone)Its claim has expired (
acquired_untilis less than the current datetime)It is claimed by the given scheduler (
acquired_byequalsscheduler_id)
- Parameters:
- Return type:
- Returns:
the list of claimed schedules
- async add_job(job)
Add a job to be executed by an eligible scheduler.
- async add_schedule(schedule, conflict_policy)
Add or update the given schedule in the data store.
- Parameters:
schedule (
Schedule) – schedule to be addedconflict_policy (
ConflictPolicy) – policy that determines what to do if there is an existing schedule with the same ID
- Return type:
- 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).
- 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_atis less or equal to the current time)Release jobs with expired leases with the
cancelledoutcomePurge finished schedules (where
next_run_timeisNone) that have no running jobs associated with them
- Return type:
- async extend_acquired_job_leases(scheduler_id, job_ids, duration)
Extend the leases of specified jobs acquired by the given scheduler.
- async extend_acquired_schedule_leases(scheduler_id, schedule_ids, duration)
Extend the leases of specified schedules acquired by the given scheduler.
- async get_job_result(job_id)
Retrieve the result of a job.
The result is removed from the store after retrieval.
- async get_jobs(ids=None)
Get the list of pending jobs.
- async get_next_schedule_run_time()
Return the earliest upcoming run time of all the schedules in the store, or
Noneif there are no active schedules.- Return type:
Optional[datetime.datetime]
- async get_schedules(ids=None)
Get schedules from the data store.
- async get_task(task_id)
Get an existing task definition.
- Parameters:
task_id (
str) – ID of the task to be returned- Return type:
- Returns:
the matching task
- Raises:
TaskLookupError – if no matching task was found
- async get_tasks()
Get all the tasks in this store.
- 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
JobReleasedevents are published.This method is called once during the scheduler startup sequence.
- async release_job(scheduler_id, job, result)
Release the claim on the given job and record the result.
- 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_timenext_fire_timetriggeracquired_by(must beset toNone)acquired_until(must be set toNone)
- Parameters:
scheduler_id (
str) – unique identifier of the schedulerresults (
Sequence[ScheduleResult]) – list of schedule processing results
- Return type:
- async remove_schedules(ids, *, finished=False)
Remove schedules from the data store.
- 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:
- 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 eitherOSErrororsqlalchemy.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:
- Return type:
- 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_untilisNone)Its claim has expired (
acquired_untilis less than the current datetime)It is claimed by the given scheduler (
acquired_byequalsscheduler_id)
- Parameters:
- Return type:
- Returns:
the list of claimed schedules
- async add_job(job)
Add a job to be executed by an eligible scheduler.
- async add_schedule(schedule, conflict_policy)
Add or update the given schedule in the data store.
- Parameters:
schedule (
Schedule) – schedule to be addedconflict_policy (
ConflictPolicy) – policy that determines what to do if there is an existing schedule with the same ID
- Return type:
- 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).
- 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_atis less or equal to the current time)Release jobs with expired leases with the
cancelledoutcomePurge finished schedules (where
next_run_timeisNone) that have no running jobs associated with them
- Return type:
- async extend_acquired_job_leases(scheduler_id, job_ids, duration)
Extend the leases of specified jobs acquired by the given scheduler.
- async extend_acquired_schedule_leases(scheduler_id, schedule_ids, duration)
Extend the leases of specified schedules acquired by the given scheduler.
- async get_job_result(job_id)
Retrieve the result of a job.
The result is removed from the store after retrieval.
- async get_jobs(ids=None)
Get the list of pending jobs.
- async get_next_schedule_run_time()
Return the earliest upcoming run time of all the schedules in the store, or
Noneif there are no active schedules.- Return type:
Optional[datetime.datetime]
- async get_schedules(ids=None)
Get schedules from the data store.
- async get_task(task_id)
Get an existing task definition.
- Parameters:
task_id (
str) – ID of the task to be returned- Return type:
- Returns:
the matching task
- Raises:
TaskLookupError – if no matching task was found
- async get_tasks()
Get all the tasks in this store.
- 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
JobReleasedevents are published.This method is called once during the scheduler startup sequence.
- async release_job(scheduler_id, job, result)
Release the claim on the given job and record the result.
- 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_timenext_fire_timetriggeracquired_by(must beset toNone)acquired_until(must be set toNone)
- Parameters:
scheduler_id (
str) – unique identifier of the schedulerresults (
Sequence[ScheduleResult]) – list of schedule processing results
- Return type:
- async remove_schedules(ids)
Remove schedules from the data store.
- 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:
- 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 downevent_broker (
EventBroker) – the event broker shared between the scheduler, scheduler (if any) and this data storelogger (
Logger) – the logger object the data store should use to log events
- Return type:
- 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 raisespymongo.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:
- Return type:
- 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_untilisNone)Its claim has expired (
acquired_untilis less than the current datetime)It is claimed by the given scheduler (
acquired_byequalsscheduler_id)
- Parameters:
- Return type:
- Returns:
the list of claimed schedules
- async add_job(job)
Add a job to be executed by an eligible scheduler.
- async add_schedule(schedule, conflict_policy)
Add or update the given schedule in the data store.
- Parameters:
schedule (
Schedule) – schedule to be addedconflict_policy (
ConflictPolicy) – policy that determines what to do if there is an existing schedule with the same ID
- Return type:
- 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).
- 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_atis less or equal to the current time)Release jobs with expired leases with the
cancelledoutcomePurge finished schedules (where
next_run_timeisNone) that have no running jobs associated with them
- Return type:
- async extend_acquired_job_leases(scheduler_id, job_ids, duration)
Extend the leases of specified jobs acquired by the given scheduler.
- async extend_acquired_schedule_leases(scheduler_id, schedule_ids, duration)
Extend the leases of specified schedules acquired by the given scheduler.
- async get_job_result(job_id)
Retrieve the result of a job.
The result is removed from the store after retrieval.
- async get_jobs(ids=None)
Get the list of pending jobs.
- async get_next_schedule_run_time()
Return the earliest upcoming run time of all the schedules in the store, or
Noneif there are no active schedules.- Return type:
Optional[datetime.datetime]
- async get_schedules(ids=None)
Get schedules from the data store.
- async get_task(task_id)
Get an existing task definition.
- Parameters:
task_id (
str) – ID of the task to be returned- Return type:
- Returns:
the matching task
- Raises:
TaskLookupError – if no matching task was found
- async get_tasks()
Get all the tasks in this store.
- 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
JobReleasedevents are published.This method is called once during the scheduler startup sequence.
- async release_job(scheduler_id, job, result)
Release the claim on the given job and record the result.
- 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_timenext_fire_timetriggeracquired_by(must beset toNone)acquired_until(must be set toNone)
- Parameters:
scheduler_id (
str) – unique identifier of the schedulerresults (
Sequence[ScheduleResult]) – list of schedule processing results
- Return type:
- async remove_schedules(ids)
Remove schedules from the data store.
- 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:
- 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 downevent_broker (
EventBroker) – the event broker shared between the scheduler, scheduler (if any) and this data storelogger (
Logger) – the logger object the data store should use to log events
- Return type:
Event brokers
- class apscheduler.abc.EventBroker
Interface for objects that can be used to publish notifications to interested subscribers.
- abstractmethod async publish_local(event)
Publish an event, but only to local subscribers.
- Return type:
- 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 downlogger (
Logger) – the logger object the event broker should use to log events
- Return type:
- 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 publishedevent_types (
Iterable[type[TypeVar(T_Event, bound= Event)]] |None) – an iterable of concrete Event classes to subscribe tois_async (
bool) –Trueif the (synchronous) callback should be called on the event loop thread,Falseif it should be called in a scheduler thread. If the callback is a coroutine function, this flag is ignored.one_shot (
bool) – ifTrue, automatically unsubscribe after the first matching event
- Return type:
- class apscheduler.abc.Subscription
Represents a subscription with an event source.
If used as a context manager, unsubscribes on exit.
- 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.
- 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
NOTIFYmechanism.- Parameters:
dsn (
str) – a libpq connection string (e.g.postgres://user:pass@host:port/dbname)options (
Mapping[str,Any]) – extra keyword arguments passed toasyncpg.connection.connect()channel (
str) – theNOTIFYchannel to usemax_idle_time (
float) – maximum time to let the connection go idle, before sending aSELECT 1query 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:
- Return type:
- Returns:
the newly created event broker
- 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 downlogger (
Logger) – the logger object the event broker should use to log events
- Return type:
- 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
NOTIFYmechanism.- Parameters:
conninfo (
str) – a libpq connection string (e.g.postgres://user:pass@host:port/dbname)options (
Mapping[str,Any]) – extra keyword arguments passed topsycopg.AsyncConnection.connect()channel (
str) – theNOTIFYchannel to usemax_idle_time (
float) – maximum time (in seconds) to let the connection go idle, before sending aSELECT 1query 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:
- Return type:
- Returns:
the newly created event broker
- 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 downlogger (
Logger) – the logger object the event broker should use to log events
- Return type:
- 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 (fortcporwebsockettransports)transport (
str) – one oftcp,websocketorunix(default:tcp)client_id (
str|None) – MQTT client ID (needed to resume an MQTT session if a connection is broken)ssl (
bool|SSLContext) – eitherTrueor a custom SSL context to enable SSL/TLS,Falseto disabletopic (
str) – topic on which to send the messagessubscribe_qos (
int) – MQTT QoS to use for subscribing messagespublish_qos (
int) – MQTT QoS to use for publishing messages
- 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 downlogger (
Logger) – the logger object the event broker should use to log events
- Return type:
- 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 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 downlogger (
Logger) – the logger object the event broker should use to log events
- Return type:
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 fromserialize()- Return type:
- 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:
datetime.date(usingdatetime.date.isoformat())datetime.timedelta(usingdatetime.timedelta.total_seconds())datetime.tzinfo(by extracting the time zone name)
- Return type:
- 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:
type_tag (
int) – CBOR tag number for indicating arbitrary serialized objectdump_options (
dict[str,Any]) – keyword arguments passed tocbor2.dumps()load_options (
dict[str,Any]) – keyword arguments passed tocbor2.loads()
- deserialize(serialized)
Restore a previously serialized object from bytestring
- Parameters:
serialized (
bytes) – a bytestring previously received fromserialize()- 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:
datetime.date(usingdatetime.date.isoformat())datetime.timedelta(usingdatetime.timedelta.total_seconds())datetime.tzinfo(by extracting the time zone name)
- Return type:
- 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 inmagic_key.- Parameters:
magic_key (
str) – name of a specially handled dict key that indicates that a dict contains a serialized instance of an arbitrary typedump_options (
dict[str,Any]) – keyword arguments passed tojson.dumps()load_options (
dict[str,Any]) – keyword arguments passed tojson.loads()
- deserialize(serialized)
Restore a previously serialized object from bytestring
- Parameters:
serialized (
bytes) – a bytestring previously received fromserialize()- 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:
datetime.date(usingdatetime.date.isoformat())datetime.timedelta(usingdatetime.timedelta.total_seconds())datetime.tzinfo(by extracting the time zone name)
- Return type:
- Returns:
a bytestring that can be later restored using
deserialize()
- class apscheduler.serializers.pickle.PickleSerializer(*, protocol=4)
Uses the
picklemodule 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 fromserialize()- 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:
datetime.date(usingdatetime.date.isoformat())datetime.timedelta(usingdatetime.timedelta.total_seconds())datetime.tzinfo(by extracting the time zone name)
- Return type:
- 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 __setstate__(state)
Initialize an empty instance from an existing state.
- Return type:
- abstractmethod next()
Return the next datetime to fire on.
If no such datetime can be calculated,
Noneis 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,
Noneis 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_timewhich is the moment the trigger was created unless specifically overridden. Ifend_timeis specified, the last trigger time will be at or before that time. If noend_timehas 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 waitdays (
float) – number of days to waithours (
float) – number of hours to waitminutes (
float) – number of minutes to waitseconds (
float) – number of seconds to waitmicroseconds (
float) – number of microseconds to waitstart_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,
Noneis 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
yearsandmonthsparameters 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, theweeksanddaysparameters 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
daysorweeksparameters 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_dateis 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
monthsspecified 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 havingyearsdefined 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 waitmonths (
int) – number of months to waitweeks (
int) – number of weeks to waitdays (
int) – number of days to waithour (
int) – hour to run the task atminute (
int) – minute to run the task atsecond (
int) – second to run the task atstart_date (
date|str) – first date to trigger on (defaults to current date if omitted)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,
Noneis 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:
- next()
Return the next datetime to fire on.
If no such datetime can be calculated,
Noneis 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.
- next()
Return the next datetime to fire on.
If no such datetime can be calculated,
Noneis 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:
day_of_week (
int|str|None) – number or name of weekday (0-7 or sun,mon,tue,wed,thu,fri,sat, sun)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 ontimezone (
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
CronTriggerfrom 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 weekstart_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 ontimezone (
tzinfo|str) – time zone to use for the date/time calculations (defaults to local timezone if omitted)
- Return type:
- next()
Return the next datetime to fire on.
If no such datetime can be calculated,
Noneis 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
finished –
Trueif 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:
- classmethod from_job(job, scheduler_id)
Create a new job-acquired event from a job and a scheduler ID.
- Parameters:
- Return type:
- 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 releasedscheduler_id (
str) – the ID of the scheduler that released the jobtask_id (
str) – ID of the task run by the jobschedule_id (
str|None) – ID of the schedule (if any) that created the jobscheduled_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 (Noneif the job was skipped due to missing its start deadline)outcome (
Any) – the outcome of the jobexception_type (
str|None) – the fully qualified name of the exception ifoutcomeisJobOutcome.errorexception_message (
str|None) – the result ofstr(exception)ifoutcomeisJobOutcome.errorexception_traceback (
list[str] |None) – the traceback lines from the exception ifoutcomeisJobOutcome.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 jobscheduler_id (
str) – the ID of the scheduler that acquired the jobtask_id (
str) – the job’s task IDschedule_id (
str|None) – ID of the schedule (if any) from which the job was spawnedscheduled_fire_time (
Optional[datetime.datetime]) – the time the job was scheduled to start (if the job was spawned from a schedule)
- Return type:
- Returns:
a new job-released event
Enumerated types
- class apscheduler.SchedulerRole
Bases:
EnumSpecifies 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:
EnumUsed 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:
EnumUsed 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:
EnumUsed 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:
EnumUsed 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
exceptionis 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.
- 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.