python3中用timer方法做一個簡單的定時器

python3中用timer方法做一個簡單的定時器**

先看一段簡單代碼

	from datetime import datetime
	from threading import Timer
	 #打印時間函數
	def printTime(inc):
	    print(datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
	    t = Timer(inc, printTime,(inc,))
	    t.start()
	printTime(2)

其中timer函數有3個參數,inc爲函數執行的間隔時間,prinTime調用的方法,(Inc,)爲prinTime方法的參數。

標題再來看一段代碼

'''
Created on 2013-7-31
@author: Eric
'''
import time
import threading


def timer_start():
    t = threading.Timer(1, test_func, ("Parameter1",))
    t.start()


def test_func(msg1):
    print("I'm test_func,", msg1)
    timer_start()


def timer2():
    timer_start()
    while True:
        time.sleep(1)


if __name__ == "__main__":
    timer2()

運行結果爲:
I’m test_func, Parameter1
I’m test_func, Parameter1
I’m test_func, Parameter1
I’m test_func, Parameter1

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章