import datetime
import sched
import threading
import time
def init():
global s
s = sched.scheduler(time.time,time.sleep)
def job1():
print("i am working in job1")
def job2():
print("i am working in job2")
def task1():
threading.Thread(target=job1).start()
s.enter(2,1,task1)
def task2():
threading.Thread(target=job2).start()
s.enter(5,1,task2)
def main():
init()
s.enter(2,1,task1)
s.enter(5,1,task2)
s.run()
print(time.time)
if __name__=="__main__":
main()
很明显,这样使用sched.scheduler中的run() 会对线程进行阻塞,最后的print(time.time)迟迟没法打印出来。
import datetime
import sched
import threading
import time
def job1():
print("i am working in job1")
def job2():
print("i am working in job2")
def task1():
s1 = sched.scheduler(time.time,time.sleep)
s1.enter(2,1,job1)
s1.run()
def task2():
s2 = sched.scheduler(time.time,time.sleep)
s2.enter(5,1,job2)
s2.run()
def main():
print("start")
threading.Thread(target=task1).start()
threading.Thread(target=task2).start()
print("end")
if __name__=="__main__":
main()
明显,把scheduler放进子线程实现,可避免对主线程的阻塞。
另外,可以通过setDaemon(True) 把线程设置为后台进程,例如:
t3=threading.Thread(target=task3)
t3.setDaemon(True)#设置为后台线程,这里默认是False,设置为True之后则主线程不用等待子线程.
t3.start()