admin管理员组

文章数量:1794759

python schedule任务未跑完

python schedule任务未跑完

python中有一个轻量级的定时任务调度的库:schedule。他可以完成每分钟,每小时,每天,周几,特定日期的定时任务。因此十分方便我们执行一些轻量级的定时任务.

代码如下:

import schedule

import time

def job(name):

print("her name is : ", name)

name = "longsongpong"

schedule.every(10).minutes.do(job, name)

schedule.every().hour.do(job, name)

schedule.every().day.at("10:30").do(job, name)

schedule.every(5).to(10).days.do(job, name)

schedule.every().monday.do(job, name)

schedule.every().wednesday.at("13:15").do(job, name)

while True:

schedule.run_pending()

time.sleep(1)每隔十分钟执行一次任务

每隔一小时执行一次任务

每天的10:30执行一次任务

每隔5到10天执行一次任务

每周一的这个时候执行一次任务

每周三13:15执行一次任务

run_pending:运行所有可以运行的任务

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

schedule.every(10).seconds.do(job)

schedule.every(10).seconds.do(job2)

while True:

schedule.run_pending()

time.sleep(1)

结果如下:

I’m working… in job1 start

I’m working… in job1 end

I’m working… in job2

如果要多线程并发运行

代码如下:

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

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

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

while True:

schedule.run_pending()

time.sleep(1)

结果如下:

I'm working... in job1 start

I'm working... in job2

I'm working... in job1 start

I'm working... in job2

I'm working... in job1 end

I'm working... in job1 start

I'm working... in job2

本文标签: Pythonschedule未跑完