背景:python利用schedule库执行定时任务。

import schedule
import time

def myjob():
    print("I'm working...")

schedule.every(10).minutes.do(myjob)

while True:
    schedule.run_pending()
    time.sleep(1)

但是我需要获取到执行任务的返回值。然而常用的方式使用do方法返回的是job对象并不能满足我获取执行方法返回值的需求。故去扒拉源码,想到一种实现方法。

具体实现:

import schedule
import time
def myjob():
    print("I'm working...")
    a ="we"
    return a
job = schedule.every(2).seconds
job.job_func =myjob
schedule.jobs.append(job)
result =job.run()
print(result)
while True:
    runnable_jobs = (job for job in schedule.jobs if job.should_run)
    for job in sorted(runnable_jobs):
        result =job.run()
        print(result)
    time.sleep(1)

 

更多推荐

python任务调度之schedule 获取执行任务的返回值