APScheduler API -- apscheduler.schedulers.base

本文详细介绍了APScheduler的使用方法,包括如何配置调度器、添加执行器、添加作业存储、监听事件等。此外还介绍了如何修改、暂停、恢复作业以及如何重新配置、启动、关闭调度器。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

apscheduler.schedulers.base

API

class apscheduler.schedulers.base. BaseScheduler ( gconfig={}, **options )

Abstract base class for all schedulers. Takes the following keyword arguments:

Parameters:
  • logger (str|logging.Logger) – logger to use for the scheduler’s logging (defaults to apscheduler.scheduler)
  • timezone (str|datetime.tzinfo) – the default time zone (defaults to the local timezone)
  • job_defaults (dict) – default values for newly added jobs
  • jobstores (dict) – a dictionary of job store alias -> job store instance or configuration dict
  • executors (dict) – a dictionary of executor alias -> executor instance or configuration dict
add_executor ( executor, alias='default', **executor_opts )

Adds an executor to this scheduler. Any extra keyword arguments will be passed to the executor plugin’s constructor, assuming that the first argument is the name of an executor plugin.

Parameters:
  • executor (str|unicode|apscheduler.executors.base.BaseExecutor) – either an executor instance or the name of an executor plugin
  • alias (str|unicode) – alias for the scheduler
Raises ValueError:
 

if there is already an executor by the given alias

add_job ( func, trigger=None, args=None, kwargs=None, id=None, name=None, misfire_grace_time=undefined, coalesce=undefined, max_instances=undefined, next_run_time=undefined, jobstore='default', executor='default', replace_existing=False, **trigger_args )

Adds the given job to the job list and wakes up the scheduler if it’s already running.

Any option that defaults to undefined will be replaced with the corresponding default value when the job is scheduled (which happens when the scheduler is started, or immediately if the scheduler is already running).

The func argument can be given either as a callable object or a textual reference in the package.module:some.object format, where the first half (separated by :) is an importable module and the second half is a reference to the callable object, relative to the module.

The trigger argument can either be:
  1. the alias name of the trigger (e.g. date, interval or cron), in which case any extra keyword arguments to this method are passed on to the trigger’s constructor
  2. an instance of a trigger class
Parameters:
  • func – callable (or a textual reference to one) to run at the given time
  • trigger (str|apscheduler.triggers.base.BaseTrigger) – trigger that determines when func is called
  • args (list|tuple) – list of positional arguments to call func with
  • kwargs (dict) – dict of keyword arguments to call func with
  • id (str|unicode) – explicit identifier for the job (for modifying it later)
  • name (str|unicode) – textual description of the job
  • misfire_grace_time (int) – seconds after the designated run time that the job is still allowed to be run
  • coalesce (bool) – run once instead of many times if the scheduler determines that the job should be run more than once in succession
  • max_instances (int) – maximum number of concurrently running instances allowed for this job
  • next_run_time (datetime) – when to first run the job, regardless of the trigger (pass None to add the job as paused)
  • jobstore (str|unicode) – alias of the job store to store the job in
  • executor (str|unicode) – alias of the executor to run the job with
  • replace_existing (bool) – True to replace an existing job with the same id (but retain the number of runs from the existing one)
Return type:

Job

add_jobstore ( jobstore, alias='default', **jobstore_opts )

Adds a job store to this scheduler. Any extra keyword arguments will be passed to the job store plugin’s constructor, assuming that the first argument is the name of a job store plugin.

Parameters:
  • jobstore (str|unicode|apscheduler.jobstores.base.BaseJobStore) – job store to be added
  • alias (str|unicode) – alias for the job store
Raises ValueError:
 

if there is already a job store by the given alias

add_listener ( callback, mask=EVENT_ALL )

Adds a listener for scheduler events. When a matching event occurs, callback is executed with the event object as its sole argument. If the mask parameter is not provided, the callback will receive events of all types.

Parameters:
  • callback – any callable that takes one argument
  • mask (int) – bitmask that indicates which events should be listened to

See also

Scheduler events

configure ( gconfig={}, prefix='apscheduler.', **options )

Reconfigures the scheduler with the given options. Can only be done when the scheduler isn’t running.

Parameters:
  • gconfig (dict) – a “global” configuration dictionary whose values can be overridden by keyword arguments to this method
  • prefix (str|unicode) – pick only those keys from gconfig that are prefixed with this string (pass an empty string or None to use all keys)
Raises SchedulerAlreadyRunningError:
 

if the scheduler is already running

get_job ( job_id, jobstore=None )

Returns the Job that matches the given job_id.

Parameters:
  • job_id (str|unicode) – the identifier of the job
  • jobstore (str|unicode) – alias of the job store that most likely contains the job
Returns:

the Job by the given ID, or None if it wasn’t found

Return type:

Job

get_jobs ( jobstore=None, pending=None )

Returns a list of pending jobs (if the scheduler hasn’t been started yet) and scheduled jobs, either from a specific job store or from all of them.

Parameters:
  • jobstore (str|unicode) – alias of the job store
  • pending (bool) – False to leave out pending jobs (jobs that are waiting for the scheduler start to be added to their respective job stores), True to only include pending jobs, anything else to return both
Return type:

list[Job]

modify_job ( job_id, jobstore=None, **changes )

Modifies the properties of a single job. Modifications are passed to this method as extra keyword arguments.

Parameters:
  • job_id (str|unicode) – the identifier of the job
  • jobstore (str|unicode) – alias of the job store that contains the job
pause_job ( job_id, jobstore=None )

Causes the given job not to be executed until it is explicitly resumed.

Parameters:
  • job_id (str|unicode) – the identifier of the job
  • jobstore (str|unicode) – alias of the job store that contains the job
print_jobs ( jobstore=None, out=sys.stdout )

Prints out a textual listing of all jobs currently scheduled on either all job stores or just a specific one.

Parameters:
  • jobstore (str|unicode) – alias of the job store, None to list jobs from all stores
  • out (file) – a file-like object to print to (defaults to sys.stdout if nothing is given)
remove_all_jobs ( jobstore=None )

Removes all jobs from the specified job store, or all job stores if none is given.

Parameters:jobstore (str|unicode) – alias of the job store
remove_executor ( alias, shutdown=True )

Removes the executor by the given alias from this scheduler.

Parameters:
  • alias (str|unicode) – alias of the executor
  • shutdown (bool) – True to shut down the executor after removing it
remove_job ( job_id, jobstore=None )

Removes a job, preventing it from being run any more.

Parameters:
  • job_id (str|unicode) – the identifier of the job
  • jobstore (str|unicode) – alias of the job store that contains the job
Raises JobLookupError:
 

if the job was not found

remove_jobstore ( alias, shutdown=True )

Removes the job store by the given alias from this scheduler.

Parameters:
  • alias (str|unicode) – alias of the job store
  • shutdown (bool) – True to shut down the job store after removing it
remove_listener ( callback )

Removes a previously added event listener.

reschedule_job ( job_id, jobstore=None, trigger=None, **trigger_args )

Constructs a new trigger for a job and updates its next run time. Extra keyword arguments are passed directly to the trigger’s constructor.

Parameters:
  • job_id (str|unicode) – the identifier of the job
  • jobstore (str|unicode) – alias of the job store that contains the job
  • trigger – alias of the trigger type or a trigger instance
resume_job ( job_id, jobstore=None )

Resumes the schedule of the given job, or removes the job if its schedule is finished.

Parameters:
  • job_id (str|unicode) – the identifier of the job
  • jobstore (str|unicode) – alias of the job store that contains the job
scheduled_job ( trigger, args=None, kwargs=None, id=None, name=None, misfire_grace_time=undefined, coalesce=undefined, max_instances=undefined, next_run_time=undefined, jobstore='default', executor='default', **trigger_args )

A decorator version of add_job(), except that replace_existing is always True.

Important

The id argument must be given if scheduling a job in a persistent job store. The scheduler cannot, however, enforce this requirement.

shutdown ( wait=True )

Shuts down the scheduler. Does not interrupt any currently running jobs.

Parameters:wait (bool) – True to wait until all currently executing jobs have finished
Raises SchedulerNotRunningError:
 if the scheduler has not been started yet
start ( )

Starts the scheduler. The details of this process depend on the implementation.

Raises SchedulerAlreadyRunningError:
 if the scheduler is already running
wakeup ( )

Notifies the scheduler that there may be jobs due for execution. Triggers _process_jobs() to be run in an implementation specific manner.

转载于:https://www.cnblogs.com/fendou-999/p/3929254.html

<think>我们正在处理关于APScheduler的使用教程或示例代码的请求。根据引用内容,我们有几个相关的引用片段:引用[1]展示了Flask-APScheduler的基本设置代码:```pythonfromflaskimportFlaskfromflask_apschedulerimportAPSchedulerclassConfig:SCHEDULER_API_ENABLED=Trueapp=Flask(__name__)app.config.from_object(Config)scheduler=APScheduler()scheduler.init_app(app)scheduler.start()if__name__=='__main__':app.run()```引用[2]说明了APScheduler的定位:它是一个跨平台的调度库,用于在现有应用程序中运行,而不是作为独立的守护进程或服务。引用[3]提到在Flask中使用APScheduler时,由于任务可能耗时,建议使用线程异步处理。但该引用没有给出具体代码。引用[4]是关于Django-APScheduler的目录结构,但没有具体使用代码。引用[5]总结了在Flask中使用APScheduler的要点:使用线程池异步处理,配置调度器、作业存储、执行器和触发器,以及使用轮询方式处理复杂步骤。用户要求的是APScheduler的使用方法或教程,而不仅仅是Flask或Django中的集成。因此,我们需要提供一个通用的APScheduler教程,同时也可以包含在Flask或Django中使用的示例。由于引用中提供了Flask-APScheduler的示例,我们可以先展示一个通用的APScheduler示例,然后展示与Flask集成的示例。###通用APScheduler使用步骤1.安装APScheduler:`pipinstallapscheduler`2.选择调度器(Scheduler)、作业存储(JobStore)、执行器(Executor)和触发器(Trigger)。3.创建调度器实例并配置。4.添加作业(Job)。5.启动调度器。###示例代码:一个简单的APScheduler脚本```pythonfromapscheduler.schedulers.blockingimportBlockingSchedulerdefmy_job():print("Hello,APScheduler!")#创建调度器实例,使用默认的作业存储(内存)和执行器(线程池)scheduler=BlockingScheduler()#添加作业,使用间隔触发器,每5秒执行一次scheduler.add_job(my_job,'interval',seconds=5)#启动调度器scheduler.start()```###在Flask中使用APScheduler(基于引用[1])在Flask中,我们可以使用Flask-APScheduler扩展,它封装了APScheduler,并提供了与Flask应用的集成。```pythonfromflaskimportFlaskfromflask_apschedulerimportAPSchedulerclassConfig:SCHEDULER_API_ENABLED=True#启用API(可选)app=Flask(__name__)app.config.from_object(Config)#初始化调度器scheduler=APScheduler()scheduler.init_app(app)#将调度器与Flask应用关联#定义一个要执行的任务defscheduled_task():print("Thistaskisrunningevery5seconds")#在调度器中添加任务scheduler.add_job(id='task1',func=scheduled_task,trigger='interval',seconds=5)#启动调度器scheduler.start()if__name__=='__main__':app.run()```注意:在Flask应用中,调度器会在启动应用时启动。上面的代码中,调度器任务在后台线程中运行,而Flask应用在主线程中运行。###在Django中使用APScheduler在Django中,通常没有像Flask-APScheduler这样的扩展,但我们可以使用自定义管理命令或应用启动时运行调度器。一个常见的做法是在Django项目的`apps.py`中,当应用准备就绪时启动调度器(注意:这依赖于Django的启动信号)。首先,安装APScheduler:`pipinstallapscheduler`然后,在一个Django应用中,修改`apps.py`:```pythonfromdjango.appsimportAppConfigfromapscheduler.schedulers.backgroundimportBackgroundSchedulerdefmy_job():print("DjangoAPSchedulerJob")classMyAppConfig(AppConfig):name='myapp'defready(self):#当Django应用准备就绪时调用scheduler=BackgroundScheduler()scheduler.add_job(my_job,'interval',seconds=5)scheduler.start()```同时,在项目的`settings.py`中,将该应用配置类完整路径加入设置:```pythonINSTALLED_APPS=[...'myapp.apps.MyAppConfig',#使用自定义的AppConfig...]```注意:在Django开发服务器中,由于自动重载机制,可能会启动多个调度器实例,因此生产环境中使用这种方式需要谨慎。另一种做法是使用自定义管理命令来启动调度器。###总结APScheduler是一个功能强大的Python调度库,可以用于各种应用场景。在Flask中,可以使用Flask-APScheduler扩展简化集成;在Django中,可以通过自定义管理命令或应用启动时初始化调度器。希望这些示例能帮助您开始使用APScheduler。§§相关问题§§1.APScheduler有哪几种调度器(Scheduler)类型?2.APScheduler支持哪些作业存储(JobStore)?3.如何避免APScheduler在Django开发服务器中重复启动?4.APScheduler的触发器(Trigger)有哪些类型?</think>### APScheduler 使用教程与示例代码 APScheduler 是一个轻量级的 Python 定时任务调度库,支持多种调度方式(如定时、间隔、cron式)。以下是核心使用方法和示例: #### 一、基础安装 ```bash pip install apscheduler ``` #### 二、核心组件 1. **调度器 (Scheduler)** 管理任务调度,常用类型: - `BlockingScheduler`:阻塞式(适合独立脚本) - `BackgroundScheduler`:后台运行(适合集成到应用) - `AsyncIOScheduler`:异步IO环境 2. **触发器 (Trigger)** 定义任务执行时机: - `date`:单次执行 `(trigger='date', run_date=datetime(2023,10,1))` - `interval`:间隔执行 `(trigger='interval', seconds=30)` - `cron`:类cron表达式 `(trigger='cron', hour=9, minute=30)` 3. **作业存储 (Job Store)** 支持内存、SQLAlchemy、Redis等 4. **执行器 (Executor)** 控制任务执行方式(线程池/进程池) --- ### 示例代码 #### 示例1:基础定时任务 ```python from apscheduler.schedulers.blocking import BlockingScheduler from datetime import datetime def job(): print(f"执行任务: {datetime.now()}") scheduler = BlockingScheduler() # 每10秒执行一次 scheduler.add_job(job, 'interval', seconds=10) scheduler.start() ``` #### 示例2:Flask集成(基于引用[1][3]) ```python from flask import Flask from flask_apscheduler import APScheduler app = Flask(__name__) scheduler = APScheduler() # 配置(启用API和任务) app.config["SCHEDULER_API_ENABLED"] = True app.config["JOBS"] = [{ "id": "task1", "func": "module:periodic_task", # 模块:函数名 "trigger": "cron", "hour": 14 }] scheduler.init_app(app) scheduler.start() def periodic_task(): print("每日14点执行的任务") if __name__ == '__main__': app.run() ``` #### 示例3:Django集成(基于引用[4]) ```python # 在django_apscheduler/management/commands/run_scheduler.py from django.core.management.base import BaseCommand from apscheduler.schedulers.blocking import BlockingScheduler class Command(BaseCommand): help = '启动定时任务' def handle(self, *args, **options): scheduler = BlockingScheduler() scheduler.add_job(daily_backup, 'cron', hour=2) # 每天2点备份 scheduler.start() def daily_backup(): print("执行数据库备份") ``` --- ### 关键配置项 | 配置项 | 说明 | 示例值 | |--------|------|--------| | `SCHEDULER_JOBSTORES` | 作业存储 | `{'default': SQLAlchemyJobStore(url='sqlite:///jobs.db')}` | | `SCHEDULER_EXECUTORS` | 执行器 | `{'default': {'type': 'threadpool', 'max_workers': 20}}` | | `SCHEDULER_JOB_DEFAULTS` | 任务默认参数 | `{'coalesce': True, 'max_instances': 3}` | --- ### 最佳实践 1. **异步处理耗时任务** 如引用[3][5]所述,使用线程池避免阻塞主进程: ```python from concurrent.futures import ThreadPoolExecutor scheduler.add_executor(ThreadPoolExecutor(max_workers=5)) ``` 2. **任务持久化** 使用数据库存储任务状态(SQLite/MySQL等): ```python from apscheduler.jobstores.sqlalchemy import SQLAlchemyJobStore jobstores = {'default': SQLAlchemyJobStore(url='sqlite:///jobs.db')} scheduler = BackgroundScheduler(jobstores=jobstores) ``` 3. **错误处理** 添加任务异常监听: ```python def task_listener(event): if event.exception: print(f"任务失败: {event.job_id}") scheduler.add_listener(task_listener) ``` ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值