python3.X 使用schedule实现定时任务

1.安装schedule,安装命令如下:

pip install schedule

2.以下为普通简单的例子:
import schedule
import time
 
def job():
    print("I'm working...")
 
# 每隔5分钟执行一次任务
schedule.every(5).minutes.do(job)
# 每隔一小时执行一次任务
schedule.every().hour.do(job)
# 每天的10:30执行一次任务
schedule.every().day.at("10:30").do(job)
# 每5-10分钟执行一次任务
schedule.every(5).to(10).minutes.do(job)
# 每周一的这个时候执行一次任务
schedule.every().monday.do(job)
# 每周三的13:30执行一次任务
schedule.every().wednesday.at("13:30").do(job)
# 每分钟的这个时刻执行一次任务
schedule.every().minute.at(":17").do(job)
# 如果job函数有有参数时,这么写
schedule.every(10).seconds.do(job,"参数") 

while True:
    # 启动服务
    run_pending() 
   #运行所有可以运行的任务
    schedule.run_pending()
    time.sleep(1)

3.schedule是串行执行,如果时间重叠就会有重叠现象,但可以用多线程实现
import schedule
import time
import threading

def job():
    print("I'm working... in job1  start")
    time.sleep(15)
    print("I'm working... in job1  end")

def job2():
    print("I'm working... in job2")

def run_threaded(job_func):
     job_thread = threading.Thread(target=job_func)
     job_thread.start()
       #threading.Thread(target=loop,args=(i,loops[i]))

 schedule.every(10).seconds.do(run_threaded,job)
 schedule.every(10).seconds.do(run_threaded,job2)


while True:
    schedule.run_pending()
    time.sleep(1)
4.如果想要对线程的数量有所控制,则可以采用如下方法:
import Queue
import time
import threading
import schedule


def job():
    print("I'm working")


def worker_main():
    while 1:
        job_func = jobqueue.get()
        job_func()

jobqueue = Queue.Queue()

schedule.every(10).seconds.do(jobqueue.put, job)
schedule.every(10).seconds.do(jobqueue.put, job)
schedule.every(10).seconds.do(jobqueue.put, job)
schedule.every(10).seconds.do(jobqueue.put, job)
schedule.every(10).seconds.do(jobqueue.put, job)

worker_thread = threading.Thread(target=worker_main)
worker_thread.start()

while 1:
    schedule.run_pending()
    time.sleep(1)
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Memcached 教程 Memcached是一个自由开源的,高性能,分布式内存对象缓存系统。 Memcached...
    大熊_7d48阅读 2,541评论 0 0
  • feisky云计算、虚拟化与Linux技术笔记posts - 1014, comments - 298, trac...
    不排版阅读 3,938评论 0 5
  • Python有两个著名的包管理工具easy_install.py和pip。在Python2.7的安装包中,easy...
    呆呆滴木木菇凉阅读 15,186评论 0 5
  • 萝卜镇的秋天比其他任何地方都要漂亮。白萝卜谷中盛开着艳丽的栀子兰,没有名字的小河旁一人高的青草郁绿郁绿。白小易一个...
    暮雨归阅读 704评论 0 0
  • 2012年开始,历经三十余年高速发展的中国经济正式开启了二次创业模式,“大众创业,万众创新”成为了新一波的时代大潮...
    静888阅读 542评论 0 2