zoukankan      html  css  js  c++  java
  • python--实现定时任务

    Python 实现定时任务

    参考链接

    一、循环 sleep

    这种方式最简单,在循环里面放入要执行的任务,然后 sleep 一段时间再执行

    from datetime import datetime
    import time
    # 每n秒执行一次
    def timer(n):
        while True:
            print(datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
            time.sleep(n)
    # 5s
    timer(5)
    

    这个方法的缺点是:只能执行固定间隔时间的任务,如果有定时任务就无法完成,比如早上六点半喊我起床。并且 sleep 是一个阻塞函数,也就是说 sleep 这一段时间,啥都不能做。对服务器性能的损耗。

    二、threading模块中的Timer

    Timer 函数第一个参数是时间间隔(单位是秒,只有秒),第二个参数是要调用的函数名,第三个参数是调用函数的参数(tuple)。

    from datetime import datetime
    from threading import Timer
    # 打印时间函数
    def printTime(inc):
        print(datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
        t = Timer(inc, printTime, (inc,))
        t.start()
    # 5s
    printTime(5)
    

    三、使用sched模块

    sched 模块是 Python 内置的模块,它是一个调度(延时处理机制),每次想要定时执行某任务都必须写入一个调度。

    import sched
    import time
    from datetime import datetime
    # 初始化sched模块的 scheduler 类
    # 第一个参数是一个可以返回时间戳的函数,第二个参数可以在定时未到达之前阻塞。
    schedule = sched.scheduler(time.time, time.sleep)
    # 被周期性调度触发的函数
    def printTime(inc):
        print(datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
        schedule.enter(inc, 0, printTime, (inc,))
    # 默认参数60s
    def main(inc=60):
        # enter四个参数分别为:间隔事件、优先级(用于同时间到达的两个事件同时执行时定序)、被调用触发的函数,
        # 给该触发函数的参数(tuple形式)
        schedule.enter(0, 0, printTime, (inc,))
        schedule.run()
    # 10s 输出一次
    main(10)
    

    sched 使用步骤如下:

    • 生成调度器:
      s = sched.scheduler(time.time,time.sleep)
      第一个参数是一个可以返回时间戳的函数,第二个参数可以在定时未到达之前阻塞。

    • 加入调度事件
      其实有 enter、enterabs 等等,我们以 enter 为例子。
      s.enter(x1,x2,x3,x4)
      四个参数分别为:间隔事件、优先级(用于同时间到达的两个事件同时执行时定序)、被调用触发的函数,给触发函数的参数(注意:一定要以 tuple 给,如果只有一个参数就(xx,))

    • 运行
      s.run()
      注意 sched 模块不是循环的,一次调度被执行后就 Over 了,如果想再执行,请再次 enter

    四、定时任务框架APScheduler学习详解

    参考链接

    一、APScheduler简介

    • 背景

      在平常的工作中几乎有一半的功能模块都需要定时任务来推动,例如项目中有一个定时统计程序,定时爬出网站的URL程序,定时检测钓鱼网站的程序等等,都涉及到了关于定时任务的问题,第一时间想到的是利用time模块的time.sleep()方法使程序休眠来达到定时任务的目的,虽然这样也可以,但是总觉得不是那么的专业,_所以就找到了python的定时任务模块APScheduler:

    • APScheduler基于Quartz的一个Python定时任务框架,实现了Quartz的所有功能,使用起来十分方便。提供了基于日期固定时间间隔以及crontab类型的任务,并且可以持久化任务, 并以 daemon 方式运行应用。基于这些功能,我们可以很方便的实现一个python定时任务系统。

    二、安装

    使用 APScheduler 需要安装

    • 利用pip进行安装
    pip install apscheduler
    

    三、APScheduler有四种组成部分:

    • 触发器(trigger)包含调度逻辑,每一个任务有它自己的触发器,用于决定接下来哪一个任务会运行。除了他们自己初始配置意外,触发器完全是无状态的。APScheduler 有三种内建的 trigger:
      • date: 特定的时间点触发
      • interval: 固定时间间隔触发
      • cron: 在特定时间周期性地触发
    • 任务存储(job store)存储被调度的任务,默认的任务存储是简单地把任务保存在内存中,其他的任务存储是将任务保存在数据库中。一个任务的数据讲在保存在持久化任务存储时被序列化,并在加载时被反序列化。调度器不能分享同一个任务存储。
    • 执行器(executor)处理任务的运行,他们通常通过在任务中提交制定的可调用对象到一个线程或者进城池来进行。当任务完成时,执行器将会通知调度器。最常用的 executor 有两种:
      • ProcessPoolExecutor
      • ThreadPoolExecutor
    • 调度器(scheduler)是其他的组成部分。你通常在应用只有一个调度器,应用的开发者通常不会直接处理任务存储、调度器和触发器,相反,调度器提供了处理这些的合适的接口。配置任务存储和执行器可以在调度器中完成,例如添加、修改和移除任务。

    四、简单应用

    import time
    from apscheduler.schedulers.blocking import BlockingScheduler
     
    def my_job():
        print time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
     
    sched = BlockingScheduler()
    # 每隔5s执行一次my_job函数,输出当前时间信息
    sched.add_job(my_job, 'interval', seconds=5)
    # 时间: 周一到周五每天早上6点半, 执行my_job
    sched.add_job(my_job, 'cron', day_of_week='1-5', hour=6, minute=30)
    sched.start()
    
    # 注释
    代码中的 BlockingScheduler 是什么呢?
    
    BlockingScheduler是APScheduler中的调度器,APScheduler 中有两种常用的调度器,BlockingScheduler 和 BackgroundScheduler,当调度器是应用中唯一要运行的任务时,使用 BlockingSchedule,如果希望调度器在后台执行,使用 BackgroundScheduler。
    
    BlockingScheduler: use when the scheduler is the only thing running in your process
    BackgroundScheduler: use when you’re not using any of the frameworks below, and want the scheduler to run in the background inside your application
    AsyncIOScheduler: use if your application uses the asyncio module
    GeventScheduler: use if your application uses gevent
    TornadoScheduler: use if you’re building a Tornado application
    TwistedScheduler: use if you’re building a Twisted application
    QtScheduler: use if you’re building a Qt application
    

    五、任务操作

    1.添加任务

    上面是通过add_job()来添加任务,另外还有一种方式是通过scheduled_job()修饰器来修饰函数

    import time
    from apscheduler.schedulers.blocking import BlockingScheduler
     
    sched = BlockingScheduler()
     
    @sched.scheduled_job('interval', seconds=5)
    def my_job():
        print time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
     
    sched.start()
    

    上述代码创建了一个 BlockingScheduler,并使用默认内存存储和默认执行器。(默认选项分别是 MemoryJobStore 和 ThreadPoolExecutor,其中线程池的最大线程数为10)。配置完成后使用 start() 方法来启动。

    如果想要显式设置 job store(使用mongo存储)和 executor 可以这样写:

    # 在运行程序5秒后,第一次输出时间。
    # 在 MongoDB 中可以看到 job 的状态
    
    from datetime import datetime
    from pymongo import MongoClient
    from apscheduler.schedulers.blocking import BlockingScheduler
    from apscheduler.jobstores.memory import MemoryJobStore
    from apscheduler.jobstores.mongodb import MongoDBJobStore
    from apscheduler.executors.pool import ThreadPoolExecutor, ProcessPoolExecutor
    # MongoDB 参数
    host = '127.0.0.1'
    port = 27017
    client = MongoClient(host, port)
    # 输出时间
    def job():
        print(datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
    # 存储方式
    jobstores = {
        'mongo': MongoDBJobStore(collection='job', database='test', client=client),
        'default': MemoryJobStore()
    }
    executors = {
        'default': ThreadPoolExecutor(10),
        'processpool': ProcessPoolExecutor(3)
    }
    job_defaults = {
        'coalesce': False,
        'max_instances': 3
    }
    scheduler = BlockingScheduler(jobstores=jobstores, executors=executors, job_defaults=job_defaults)
    scheduler.add_job(job, 'interval', seconds=5, jobstore='mongo')
    scheduler.start()
    

    2.删除任务

    job = scheduler.add_job(myfunc, 'interval', minutes=2)
    job.remove()
    #如果有多个任务序列的话可以给每个任务设置ID号,可以根据ID号选择清除对象,且remove放到start前才有效
    sched.add_job(myfunc, 'interval', minutes=2, id='my_job_id')
    sched.remove_job('my_job_id')
    

    3. 暂停和恢复任务

    • 暂停任务

      apsched.job.Job.pause()
      apsched.schedulers.base.BaseScheduler.pause_job()
      
    • 恢复任务

      apsched.job.Job.resume()
      apsched.schedulers.base.BaseScheduler.resume_job()
      

    4.获取job列表

    获得调度任务的列表,可以使用get_jobs()来完成,它会返回所有的job实例。或者使用print_jobs()来输出所有格式化的任务列表。也可以利用get_job(任务ID)获取指定任务的任务列表

    job = sched.add_job(my_job, 'interval', seconds=2 ,id='123')
    print sched.get_job(job_id='123')
    print sched.get_jobs()
    

    5.关闭调度器

    默认情况下调度器会等待所有正在运行的任务完成后,关闭所有的调度器和任务存储。如果你不想等待,可以将wait选项设置为False。

    sched.shutdown()
    sched.shutdown(wait=False)
    

    6.scheduler 事件

    scheduler 可以添加事件监听器,并在特殊的时间触发。

    def my_listener(event):
        if event.exception:
            print('The job crashed :(')
        else:
            print('The job worked :)')
    # 添加监听器
    scheduler.add_listener(my_listener, EVENT_JOB_EXECUTED | EVENT_JOB_ERROR)
    

    六、任务运行控制

    add_job的第二个参数是trigger,它管理着任务的调度方式。它可以为date, interval或者cron。对于不同的trigger,对应的参数也相同。

    1. cron定时调度(某一定时时刻执行)

    # 说明
    
    (int|str) 表示参数既可以是int类型,也可以是str类型
    (datetime | str) 表示参数既可以是datetime类型,也可以是str类型
    
    • year (int|str) – 4-digit year -(表示四位数的年份,如2008年)

    • month (int|str) – month (1-12) -(表示取值范围为1-12月)

    • day (int|str) – day of the (1-31) -(表示取值范围为1-31日)

    • week (int|str) – ISO week (1-53) -(格里历2006年12月31日可以写成2006年-W52-7(扩展形式)或2006W527(紧凑形式))

    • day_of_week (int|str) – number or name of weekday (0-6 or mon,tue,wed,thu,fri,sat,sun) - (表示一周中的第几天,既可以用0-6表示也可以用其英语缩写表示)

    • hour (int|str) – hour (0-23) - (表示取值范围为0-23时)

    • minute (int|str) – minute (0-59) - (表示取值范围为0-59分)

    • second (int|str) – second (0-59) - (表示取值范围为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) -(表示时区取值)

    • 案例

      #表示2020年7月22日17时19分07秒执行该程序
      sched.add_job(my_job, 'cron', year=2020,month = 7,day = 22,hour = 17,minute = 19,second = 7)
       
      #表示任务在6,7,8,11,12月份的第三个星期五的00:00,01:00,02:00,03:00 执行该程序
      sched.add_job(my_job, 'cron', month='6-8,11-12', day='3rd fri', hour='0-3')
       
      #表示从星期一到星期五5:30(AM)直到2020-08-30 00:00:00
      sched.add_job(my_job(), 'cron', day_of_week='mon-fri', hour=5, minute=30,end_date='2020-08-30')
       
      #表示每5秒执行该程序一次,相当于interval 间隔调度中seconds = 5
      sched.add_job(my_job, 'cron',second = '*/5')
      

    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
    
    • 案例

      #表示每隔3天17时19分07秒执行一次任务
      sched.add_job(my_job, 'interval',days  = 3,hours = 17,minutes = 19,seconds = 7)
      
      from datetime import datetime
      from apscheduler.schedulers.blocking import BlockingScheduler
      
      def job_function():
          print("Hello World")
          
      # BlockingScheduler
      sched = BlockingScheduler()
      
      # Schedule job_function to be called every two hours
      sched.add_job(job_function, 'interval', hours=2)
      
      # The same as before, but starts on 2010-10-10 at 9:30 and stops on 2014-06-15 at 11:00
      sched.add_job(job_function, 'interval', hours=2, start_date='2010-10-10 09:30:00', end_date='2014-06-15 11:00:00')
      
      sched.start()
      

    3.date 定时调度(作业只会执行一次)

    最基本的一种调度,作业只会执行一次。它的参数如下:

    • run_date (datetime|str) – the date/time to run the job at -(任务开始的时间)

    • timezone (datetime.tzinfo|str) – time zone for run_date if it doesn’t have one already

    • 案例

      from datetime import date
      from apscheduler.schedulers.blocking import BlockingScheduler
      sched = BlockingScheduler()
      def my_job(text):
          print(text)
      # The job will be executed on November 6th, 2009
      sched.add_job(my_job, 'date', run_date=date(2009, 11, 6), args=['text'])
      sched.add_job(my_job, 'date', run_date=datetime(2009, 11, 6, 16, 30, 5), args=['text'])
      sched.add_job(my_job, 'date', run_date='2009-11-06 16:30:05', args=['text'])
      # The 'date' trigger and datetime.now() as run_date are implicit
      sched.add_job(my_job, args=['text'])
      sched.start()
      
  • 相关阅读:
    11. Container With Most Water
    9. Palindrome Number
    375. 猜数字大小 II leetcode java
    leetcode 72 编辑距离 JAVA
    73. 矩阵置零 leetcode JAVA
    快速排序 JAVA实现
    63. 不同路径 II leetcode JAVA
    重写(override)与重载(overload)
    62 不同路径 leetcode JAVA
    leetcode 56 合并区间 JAVA
  • 原文地址:https://www.cnblogs.com/yblackd/p/13359769.html
Copyright © 2011-2022 走看看