python定時器
阿新 • • 發佈:2018-12-30
只執行一次的定時器
再主函式中
2秒後執行show這個函式並傳入引數thime,如果不想傳入引數
上面程式碼中是使用了myshow和myshow2兩個定時器,如果想使用一個變數和再一些時間後想要停止定時器
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import threading
def main():
myshow = threading.Timer(2,lambda :show("thime"))
myshow.start()
def show(text):
print "hello"+str(text)
if __name__ == '__main__':
main()
再主函式中
myshow = threading.Timer(2,lambda :show("thime"))
2秒後執行show這個函式並傳入引數thime,如果不想傳入引數
myshow = threading.Timer(2,show)
再把show方法中的引數改寫一下。
上面只是執行一次如果想執行多次,
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import threading
def main():
myshow = threading.Timer(2,show)
myshow.start()
def show():
print "hello time!"
myshow2 = threading.Timer(2,show)
myshow2.start()
if __name__ == '__main__':
main()
上面程式碼中是使用了myshow和myshow2兩個定時器,如果想使用一個變數和再一些時間後想要停止定時器
主函式再沉睡5秒後,關閉定時器#!/usr/bin/python # -*- coding: UTF-8 -*- import threading import time def main(): global myshow myshow = threading.Timer(2,show) myshow.start() # 5秒後停止定時器 time.sleep(5) myshow.cancel() def show(): print "hello time!" global myshow myshow = threading.Timer(2,show) myshow.start() if __name__ == '__main__': main()
myshow.cancel()