python中APScheduler的使用详解(python3经典编程案例)

简介: 文章详细讲解了在Python中使用APScheduler来安排和执行定时任务的方法,包括不同调度器的配置与使用场景。

一. 介绍及基本案例

APScheduler用起来十分方便,提供了基于日期,时间间隔及crontab类型的任务。为我们提供了构建专用调度器或者调度服务的基础模块。

APScheduler不是一个守护进程或服务,它自身不带有任何命令行工具。它主要在现有的程序中运行,

安装:pip3 install apscheduler

一个简单的任务间隔实例

# -*- coding: utf-8 -*-
import os
from datetime import datetime
from apscheduler.schedulers.blocking import BlockingScheduler


def tick():
    print('Tick! The time is: %s' % datetime.now())


if __name__ == '__main__':
    scheduler = BlockingScheduler()
    scheduler.add_job(tick, 'interval', seconds=3)
    print('Press Ctrl+{0} to exit'.format('Break' if os.name == 'nt' else 'C    '))

    try:
        scheduler.start()
    except (KeyboardInterrupt, SystemExit):
        pass

二. cron类的定时任务

文档地址:https://apscheduler.readthedocs.io/en/latest/modules/triggers/cron.html

Parameters:
year (int|str) – 4-digit year
month (int|str) – month (1-12)
day (int|str) – day of month (1-31)
week (int|str) – ISO week (1-53)
day_of_week (int|str) – number or name of weekday (0-6 or mon,tue,wed,thu,fri,sat,sun)
hour (int|str) – hour (0-23)
minute (int|str) – minute (0-59)
second (int|str) – second (0-59)
start_date (datetime|str) – earliest possible date/time to trigger on (inclusive)
end_date (datetime|str) – latest possible date/time to trigger on (inclusive)
timezone (datetime.tzinfo|str) – time zone to use for the date/time calculations (defaults to scheduler timezone)
jitter (int|None) – delay the job execution by jitter seconds at most

# -*- coding: utf-8 -*-

from datetime import datetime
import os
from apscheduler.schedulers.blocking import BlockingScheduler


def tick():
    print('Tick! The time is: %s' % datetime.now())


if __name__ == '__main__':
    scheduler = BlockingScheduler()
    # 每天8点40执行任务
    scheduler.add_job(tick, 'cron', hour=18, minute=40)
    print('Press Ctrl+{0} to exit'.format('Break' if os.name == 'nt' else 'C    '))

    try:
        scheduler.start()
    except (KeyboardInterrupt, SystemExit):
        pass

任务定时参考:

minute = '*/3'  # 表示每5分钟执行一次
hour = '19-21', minute = '23'  # 表示19:23, 20:23, 21:23 各执行一次任务

三. 调度器事件监听

APScheduler监听代码异常并记录到日志文件:

# -*- coding: utf-8 -*-
# File Name: listen_event.py

from apscheduler.schedulers.blocking import BlockingScheduler
from apscheduler.events import EVENT_JOB_EXECUTED, EVENT_JOB_ERROR
import datetime
import logging

logging.basicConfig(level=logging.INFO,
                    format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
                    datefmt='%Y-%m-%d %H:%M:%S',
                    filename='log1.txt',
                    filemode='a')


def aps_test(x):
    print(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'), x)


def date_test(x):
    print(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'), x)
    print(1/0)


def my_listener(event):
    if event.exception:
        print('任务出错了!!!!!!')
    else:
        print('任务照常运行...')


scheduler = BlockingScheduler()
scheduler.add_job(func=date_test, args=('一次性任务,会出错',), next_run_time=datetime.datetime.now() + datetime.timedelta(seconds=15), id='date_task')
scheduler.add_job(func=aps_test, args=('循环任务',), trigger='interval', seconds=3, id='interval_task')
scheduler.add_listener(my_listener, EVENT_JOB_EXECUTED | EVENT_JOB_ERROR)
scheduler._logger = logging
scheduler.start()

四. 配置调度器并使用

4.1 使用默认的作业存储器

# -*- coding: utf-8 -*-

from apscheduler.schedulers.blocking import BlockingScheduler
import datetime
from apscheduler.jobstores.memory import MemoryJobStore
from apscheduler.executors.pool import ThreadPoolExecutor, ProcessPoolExecutor


def my_job(id='my_job'):
    print(id,'-->',datetime.datetime.now())
jobstores = {
   
    'default': MemoryJobStore()

}
executors = {
   
    'default': ThreadPoolExecutor(20),
    'processpool': ProcessPoolExecutor(10)
}
job_defaults = {
   
    'coalesce': False,
    'max_instances': 3
}
scheduler = BlockingScheduler(jobstores=jobstores, executors=executors, job_defaults=job_defaults)
scheduler.add_job(my_job, args=['job_interval',],id='job_interval',trigger='interval', seconds=5,replace_existing=True)
scheduler.add_job(my_job, args=['job_cron',],id='job_cron',trigger='cron',month='4-8,11-12',hour='7-11', second='*/10',\
                  end_date='2020-05-30')
scheduler.add_job(my_job, args=['job_once_now',],id='job_once_now')
scheduler.add_job(my_job, args=['job_date_once',],id='job_date_once',trigger='date',run_date='2018-04-05 07:48:05')
try:
    scheduler.start()
except SystemExit:
    print('exit')
    exit()

4.2 使用数据库作为作业存储器

# -*- coding: utf-8 -*-

from apscheduler.schedulers.blocking import BlockingScheduler
import datetime
from apscheduler.jobstores.memory import MemoryJobStore
from apscheduler.executors.pool import ThreadPoolExecutor, ProcessPoolExecutor
from apscheduler.jobstores.sqlalchemy import SQLAlchemyJobStore
def my_job(id='my_job'):
    print (id,'-->',datetime.datetime.now())
jobstores = {
   
    'default': SQLAlchemyJobStore(url='sqlite:///jobs.sqlite')
}
executors = {
   
    'default': ThreadPoolExecutor(20),
    'processpool': ProcessPoolExecutor(10)
}
job_defaults = {
   
    'coalesce': False,
    'max_instances': 3
}
scheduler = BlockingScheduler(jobstores=jobstores, executors=executors, job_defaults=job_defaults)
scheduler.add_job(my_job, args=['job_interval',],id='job_interval',trigger='interval', seconds=5,replace_existing=True)
scheduler.add_job(my_job, args=['job_cron',],id='job_cron',trigger='cron',month='4-8,11-12',hour='7-11', second='*/10',\
                  end_date='2018-05-30')
scheduler.add_job(my_job, args=['job_once_now',],id='job_once_now')
scheduler.add_job(my_job, args=['job_date_once',],id='job_date_once',trigger='date',run_date='2018-04-05 07:48:05')
try:
    scheduler.start()
except SystemExit:
    print('exit')
    exit()
相关文章
|
1天前
|
机器学习/深度学习 数据采集 数据挖掘
探索Python编程的奥秘
【10月更文挑战第7天】本文将带你走进Python的世界,探索其背后的逻辑与魅力。我们将从基础语法开始,逐步深入到函数、面向对象编程等高级特性,最后通过实际项目案例,让你体验Python的强大与便捷。无论你是编程新手,还是有一定基础的开发者,都能在这篇文章中找到你需要的信息和启发。
|
2天前
|
IDE 开发工具 Python
Python 编程入门:打造你的第一个程序
【10月更文挑战第6天】编程,这个听起来高大上又充满神秘感的领域,其实就像学习骑自行车一样。一开始你可能会觉得难以掌握平衡,但一旦你学会了,就能自由地穿梭在广阔的道路上。本文将带你走进 Python 的世界,用最简单的方式让你体验编写代码的乐趣。不需要复杂的理论,我们将通过一个简单的例子——制作一个猜数字游戏,来实践学习。准备好了吗?让我们开始吧!
|
3天前
|
存储 人工智能 数据挖掘
探索Python编程:从基础到进阶
【10月更文挑战第5天】在数字时代的浪潮中,掌握编程技能已成为一项宝贵的能力。本文旨在为初学者提供一个深入浅出的Python编程之旅,从基本概念到实际应用,逐步揭示编程之美。无论你是编程新手还是希望深化理解,跟随这篇文章的脚步,你将学会如何用Python语言构建你的第一个程序,并了解代码背后的逻辑。让我们开始吧,解锁编程的秘密,开启你的技术成长之路!
|
3天前
|
数据采集 程序员 开发者
Python编程入门:从基础到实战
【10月更文挑战第5天】本文旨在为初学者提供一条清晰的Python学习路径,涵盖基础知识、关键概念、实战项目以及常见问题解答。我们将通过简单易懂的语言和实际代码示例,帮助读者快速掌握Python编程技能。无论你是零基础的新手还是有一定经验的开发者,都能在这篇文章中找到有价值的信息。让我们一起开启Python编程之旅吧!
|
1天前
|
设计模式 缓存 Python
Python编程中的装饰器:从基础到高级应用
【10月更文挑战第7天】 本文深入探讨了Python中装饰器的使用,从基本概念到高级应用全面解析。通过具体示例,读者将能清晰理解装饰器的本质、实现方式及其在代码优化和功能增强中的重要作用。
6 0
|
2天前
|
存储 算法 API
Python学习五:函数、参数(必选、可选、可变)、变量、lambda表达式、内置函数总结、案例
这篇文章是关于Python函数、参数、变量、lambda表达式、内置函数的详细总结,包含了基础知识点和相关作业练习。
11 0
|
Python
Python编程:定时任务apscheduler框架
Python编程:定时任务apscheduler框架
278 0
Python编程:定时任务apscheduler框架
|
Python
Python编程:定时任务apscheduler框架
Python编程:定时任务apscheduler框架
300 0
Python编程:定时任务apscheduler框架
|
4天前
|
存储 人工智能 Java
Python编程入门:从基础到实战
【10月更文挑战第4天】本文旨在为初学者提供一个全面而深入的Python编程学习路径。我们将从Python的基本语法和概念开始,然后逐步深入到更复杂的主题,如数据结构、面向对象编程和异常处理等。最后,我们将通过一些实际的项目案例,帮助读者将理论知识应用到实践中去。无论你是编程新手,还是有一定经验的开发者,都可以在这篇文章中找到适合自己的学习内容。让我们一起开启Python编程的学习之旅吧!
|
4天前
|
数据可视化 Python
Python编程之数据可视化入门
【10月更文挑战第4天】在数字时代的洪流中,数据如同星辰般璀璨,而将它们绘制成图表,便是我们探索宇宙的方式。本文将带你启航,用Python这艘航船,驶向数据可视化的奥秘。我们将从安装必要的工具包开始,逐步深入到数据的呈现,最后通过代码示例点亮知识的灯塔,指引你在数据海洋中航行。让我们握紧舵盘,乘风破浪,揭开数据背后的故事吧!