Dag python任务调度 python任务调度工具_应用程序


APScheduler是Python的一个定时任务框架,用于执行周期或者定时任务,可以基于日期、时间间隔,及类似于云服务器Linux系统上的定时任务crontab类型的定时任务;该框架不仅可以添加、删除定时任务,还可以将任务存储到数据库中,实现任务的持久化,使用起来非常方便。

安装方式:pip install apscheduler

pscheduler组件及简单说明:


1、triggers(触发器):触发器包含调度逻辑,每一个作业有它自己的触发器
    2、job stores(作业存储):用来存储被调度的作业,默认的作业存储器是简单地把作业任务保存在内存中,支持存储到MongoDB,Redis数据库中
    3、executors(执行器):执行器用来执行定时任务,只是将需要执行的任务放在新的线程或者线程池中运行
    4、schedulers(调度器):调度器是将其它部分联系在一起,对使用者提供接口,进行任务添加,设置,删除。


Dag python任务调度 python任务调度工具_定时任务_02


实例1 -间隔性任务


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()
    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


导入调度器模块 BlockingScheduler,这是最简单的调度器,调用 start 方阻塞当前进程,如果你的程序只用于调度,除了调度进程外没有其他后台进程,那么请用 BlockingScheduler 非常有用,此时调度进程相当于守护进程。

定义一个函数 tick 代表我们要调度的作业程序。

实例化一个 BlockingScheduler 类,不带参数表明使用默认的作业存储器-内存,默认的执行器是线程池执行器,最大并发线程数默认为 10 个(另一个是进程池执行器)。
第 11 行添加一个作业 tick,触发器为 interval,每隔 3 秒执行一次,另外的触发器为 date,cron。date 按特定时间点触发,cron 则按固定的时间间隔触发。
加入捕捉用户中断执行和解释器退出异常,pass 关键字,表示什么也不做。

测试结果如下:


Dag python任务调度 python任务调度工具_Dag python任务调度_03


实例2 -cron任务


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()
    scheduler.add_job(tick, 'cron', hour=19,minute=23)
    print('Press Ctrl+{0} to exit'.format('Break' if os.name == 'nt' else 'C    '))

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


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


配置调度器

调度器的主要循环其实就是反复检查是不是到时需要执行的任务。

询问自己的每一个作业存储器,有没有到期需要执行的任务,如果有,计算这些作业中每个作业需要运行的时间点,如果时间点有多个,做 coalesce 检查。提交给执行器按时间点运行。

在配置调度器前,我们首先要选取适合我们应用环境场景的调度器,存储器和执行器。下面是各调度器的适用场景:


BlockingScheduler:适用于调度程序是进程中唯一运行的进程,调用start函数会阻塞当前线程,不能立即返回。
BackgroundScheduler:适用于调度程序在应用程序的后台运行,调用start后主线程不会阻塞。
AsyncIOScheduler:适用于使用了asyncio模块的应用程序。
GeventScheduler:适用于使用gevent模块的应用程序。
TwistedScheduler:适用于构建Twisted的应用程序。
QtScheduler:适用于构建Qt的应用程序。
上述调度器可以满足我们绝大多数的应用环境,本文以两种调度器为例说明如何进行调度器配置。


接口云服务磁盘性能自动化测试定时任务讲解


from apscheduler.schedulers.background import BackgroundScheduler
from django_apscheduler.jobstores import DjangoJobStore, register_events, register_job

scheduler = BackgroundScheduler()
scheduler.add_jobstore(DjangoJobStore(), "default")
scheduler.start()


磁盘测试执行内容


def RunDisk(taskuuid, taskTF=False):
    res = PDCreate(taskuuid)
ret = res["ret"]
if ret == 2:
    reportuuid = res["data"]["reportuuid"]
    task_mes = models.Performance_Disk.objects.all()
    task_mes.filter(taskuuid=taskuuid).update(reportuuid=reportuuid)
if taskTF == True:
    disk_mes = models.Performance_Disk.objects.filter(taskuuid=taskuuid)
    disk_mes.update(TestStatus="执行中")
return res


添加定时任务


def diskTask(taskuuid, day, hour):
T1 = GetNewTime()
#                    月       天      时        分          秒
new_time = T1.new_times(month=0, day=day, hours=0, minutes=0, seconds=0)
end_date = str(new_time)
disk_mes = models.Performance_Disk.objects.filter(taskuuid=taskuuid)
disk_mes.update(duration=day, timing=hour, etime=end_date)
scheduler.add_job(func=RunDisk, args=[taskuuid, True], trigger='cron',
                  day_of_week='0-6', id=taskuuid, misfire_grace_time=30, max_instances=10,
                  hour=hour, end_date=end_date
                  )