原文:https://blog.csdn.net/uyy203/article/details/89684996
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() 會(huì)對(duì)線程進(jìn)行阻塞雕憔,最后的print(time.time)遲遲沒(méi)法打印出來(lái)。
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放進(jìn)子線程實(shí)現(xiàn)础芍,可避免對(duì)主線程的阻塞低矮。
另外,可以通過(guò)setDaemon(True) 把線程設(shè)置為后臺(tái)進(jìn)程曹仗,例如:
t3=threading.Thread(target=task3)
t3.setDaemon(True)#設(shè)置為后臺(tái)線程榨汤,這里默認(rèn)是False,設(shè)置為T(mén)rue之后則主線程不用等待子線程.
t3.start()