APScheduler (重点)

定时校正

  • 需求: mysql和redis两个系统, mysql增加数据成功, redis未必添加成功, 这样两个系统的数据可能出现偏差, 所以需要定期对mysql和redis的数据进行同步
  • 解决方案: 每天执行一次定时任务, 让mysql数据和redis数据进行同步

  • crontab
    • 是linux系统一个内置命令, 依赖于linux系统, 无动态管理任务(取消/暂停/修改任务配置)
    • 使用场景: 适合于普通的静态任务
  • apscheduler
    • 独立的定时器程序, 可以方便的管理定时任务
    • 使用场景: 需要动态生成/管理任务, 如下单后30分钟可有效期
    • 安装 pip install apscheduler
    • 支持三种触发器
      • date 只执行一次
      • interval 周期执行 参数 时间间隔
      • cron 周期执行 参数 时间

调度器 Scheduler

负责管理定时任务

BlockingScheduler: 作为独立进程时使用

  from apscheduler.schedulers.blocking import BlockingScheduler

  scheduler = BlockingScheduler()
  scheduler.start()  # 此处程序会发生阻塞

BackgroundScheduler: 在框架程序(如Django、Flask)中使用

  from apscheduler.schedulers.background import BackgroundScheduler

  scheduler = BackgroundScheduler()
  scheduler.start()  # 此处程序不会发生阻塞

执行器 executors

在定时任务该执行时,以进程或线程方式执行任务

ThreadPoolExecutor

  from apscheduler.executors.pool import ThreadPoolExecutor
  ThreadPoolExecutor(max_workers)  
  ThreadPoolExecutor(20) # 最多20个线程同时执行

使用方法

  executors = {
      'default': ThreadPoolExecutor(20)
  }
  scheduler = BackgroundScheduler(executors=executors)

ProcessPoolExecutor

  from apscheduler.executors.pool import ProcessPoolExecutor
  ProcessPoolExecutor(max_workers)
  ProcessPoolExecutor(5) # 最多5个进程同时执行

使用方法

  executors = {
      'default': ProcessPoolExecutor(3)
  }
  scheduler = BackgroundScheduler(executors=executors)

触发器 Trigger

指定定时任务执行的时机

1) date 在特定的时间日期执行

from datetime import date

# 在2019年11月6日00:00:00执行
sched.add_job(my_job, 'date', run_date=date(2009, 11, 6))

# 在2019年11月6日16:30:05
sched.add_job(my_job, 'date', run_date=datetime(2009, 11, 6, 16, 30, 5))
sched.add_job(my_job, 'date', run_date='2009-11-06 16:30:05')

# 立即执行
sched.add_job(my_job, 'date')  
sched.start()

2) interval 经过指定的时间间隔执行
weeks (int) – number of weeks to wait
days (int) – number of days to wait
hours (int) – number of hours to wait
minutes (int) – number of minutes to wait
seconds (int) – number of seconds to wait
start_date (datetime|str) – starting point for the interval calculation
end_date (datetime|str) – latest possible date/time to trigger on
timezone (datetime.tzinfo|str) – time zone to use for the date/time calculations

from datetime import datetime

# 每两小时执行一次
sched.add_job(job_function, 'interval', hours=2)

# 在2010年10月10日09:30:00 到2014年6月15日的时间内,每两小时执行一次
sched.add_job(job_function, 'interval', hours=2, start_date='2010-10-10 09:30:00', end_date='2014-06-15 11:00:00')

3) cron 按指定的周期执行
year (int|str) – 4-digit year
month (int|str) – month (1-12)
day (int|str) – day of the (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)

# 在6、7、8、11、12月的第三个周五的00:00, 01:00, 02:00和03:00 执行
sched.add_job(job_function, 'cron', month='6-8,11-12', day='3rd fri', hour='0-3')

# 在2014年5月30日前的周一到周五的5:30执行
sched.add_job(job_function, 'cron', day_of_week='mon-fri', hour=5, minute=30, end_date='2014-05-30')

任务管理

方式1

job = scheduler.add_job(myfunc, 'interval', minutes=2)  # 添加任务
job.remove()  # 删除任务
job.pause() # 暂定任务
job.resume()  # 恢复任务

方式2

scheduler.add_job(myfunc, 'interval', minutes=2, id='my_job_id')  # 添加任务    
scheduler.remove_job('my_job_id')  # 删除任务
scheduler.pause_job('my_job_id')  # 暂定任务
scheduler.resume_job('my_job_id')  # 恢复任务

调整任务调度周期

job.modify(max_instances=6, name='Alternate name')

scheduler.reschedule_job('my_job_id', trigger='cron', minute='*/5')

停止APScheduler运行

scheduler.shutdown()

代码

import time

from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.executors.pool import ThreadPoolExecutor

# 创建执行器  用于支持多进程/多线程
executor = ThreadPoolExecutor(max_workers=5)

# 创建调度器
scheduler = BackgroundScheduler(executors={'default': executor})


def func1(name, age):
    print(name, age)


# 添加任务
# date  只执行一次
# scheduler.add_job(func1, "date", run_date='2019-08-29 14:53:40', args=['zs', 30])
# interval 周期执行 参数是时间间隔
# scheduler.add_job(func1, "interval", seconds=10, args=['zs', 30])
# cron 周期执行 参数是时间   每月1号3点会执行一次
# scheduler.add_job(func1, "cron", day=1, hour=3, args=['zs', 30])

# 秒针每次到30时执行一次
scheduler.add_job(func1, "cron", second=30, args=['zs', 30])

# 启动调度器
scheduler.start()

while True:
    time.sleep(24 * 60 * 60)

转载于:https://www.cnblogs.com/oklizz/p/11431871.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值