欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Python定時器實例代碼

 更新時間:2017年11月01日 10:50:05   作者:saltriver  
這篇文章主要介紹了Python定時器實例代碼,向大家分享了兩部分代碼示例,一個是通過線程實現(xiàn)定時器timer,另一個是Python實現(xiàn)的精度可調的定時器實例,具有一定參考價值,需要的朋友可以了解下。

在實際應用中,我們經常需要使用定時器去觸發(fā)一些事件。Python中通過線程實現(xiàn)定時器timer,其使用非常簡單??词纠?/p>

import threading
def fun_timer():
  print('Hello Timer!')
timer = threading.Timer(1, fun_timer)
timer.start()

輸出結果:

Hello Timer!
Process finished with exit code 0

注意,只輸出了一次,程序就結束了,顯然不是我們想要的結果??碩imer類中的解釋性描述:

"""Call a function after a specified number of seconds"""

一段時間后調用一個函數,但并沒有說要循環(huán)調用該函數。因此,修改如下:

def fun_timer():
  print('Hello Timer!')
  global timer
  timer = threading.Timer(5.5, fun_timer)
  timer.start()

timer = threading.Timer(1, fun_timer)
timer.start()

輸出結果:

Hello Timer!
Hello Timer!
Hello Timer!
Hello Timer!
............

定時器工作正常。

在使用Python定時器時需要注意如下4個方面:

(1)定時器構造函數主要有2個參數,第一個參數為時間,第二個參數為函數名,第一個參數表示多長時間后調用后面第二個參數指明的函數。第二個參數注意是函數對象,進行參數傳遞,用函數名(如fun_timer)表示該對象,不能寫成函數執(zhí)行語句fun_timer(),不然會報錯。用type查看下,可以看出兩者的區(qū)別。

print(type(fun_timer()))
print(type(fun_timer))

輸出:

Hello Timer!
<class 'NoneType'>
<class 'function'>

(2)必須在定時器執(zhí)行函數內部重復構造定時器,因為定時器構造后只執(zhí)行1次,必須循環(huán)調用。

(3)定時器間隔單位是秒,可以是浮點數,如5.5,0.02等,在執(zhí)行函數fun_timer內部和外部中給的值可以不同。如上例中第一次執(zhí)行fun_timer是1秒后,后面的都是5.5秒后執(zhí)行。

(4)可以使用cancel停止定時器的工作,如下例:

# -*- coding: utf-8 -*-
import threading
import time
def fun_timer():
  print('Hello Timer!')
  global timer
  timer = threading.Timer(5.5, fun_timer)
  timer.start()
timer = threading.Timer(1, fun_timer)
timer.start()
time.sleep(15) # 15秒后停止定時器
timer.cancel()

輸出:

Hello Timer!
Hello Timer!
Hello Timer!
Process finished with exit code 0

下面是一個Python寫的定時器,定時精度可調節(jié),分享給大家。

# -* coding: utf-8 -*-
import sys
import os
import getopt
import threading
import time
def Usage():
	usage_str = '''說明:
	\t定時器
	\timer.py -h 顯示本幫助信息,也可以使用--help選項
	\timer.py -d num 指定一個延時時間(以毫秒為單位)
	\t          也可以使用--duration=num選項
	'''
	print(usage_str)
	
def args_proc(argv):
	'''處理命令行參數'''
	try:
		opts, args = getopt.getopt(sys.argv[1:], 'hd:', ['help', 'duration='])
	except getopt.GetoptError as err:
		print('錯誤!請為腳本指定正確的命令行參數。\n')
		Usage()
		sys.exit(255)
	if len(opts) < 1:
		print('使用提示:缺少必須的參數。')
		Usage()
		sys.exit(255)
	usr_argvs = {}
	for op, value in opts:
		if op in ('-h', '--help'):
			Usage()
			sys.exit(1)
		elif op in ('-d', '--duration'):
			if int(value) <= 0:
				print('錯誤!指定的參數值%s無效。\n' % (value))
				Usage()
				sys.exit(2)
			else:
				usr_argvs['-d'] = int(value)
		else:
			print('unhandled option')
			sys.exit(3)
	return usr_argvs
def timer_proc(interval_in_millisecond):
	loop_interval = 10		# 定時精度,也是循環(huán)間隔時間(毫秒),也是輸出信息刷新間隔時間,它不能大于指定的最大延時時間,否則可能導致無任何輸出
	t = interval_in_millisecond / loop_interval
	while t >= 0:
		min = (t * loop_interval) / 1000 / 60
		sec = (t * loop_interval) / 1000 % 60
		millisecond = (t * loop_interval) % 1000
		print('\rThe remaining time:%02d:%02d:%03d...' % ( min, sec, millisecond ), end = '\t\t')
		time.sleep(loop_interval / 1000)
		t -= 1
	if millisecond != 0:
		millisecond = 0
		print('\rThe remaining time:%02d:%02d:%03d...' % ( min, sec, millisecond ), end = '\t\t')
	print()
# 應用程序入口
if __name__ == '__main__':
	usr_argvs = {}
	usr_argvs = args_proc(sys.argv)
	for argv in usr_argvs:
		if argv in ( '-d', '--duration'):
			timer_proc(usr_argvs[argv])
		else:
			continue
			

總結

以上就是本文關于Python定時器實例代碼的全部內容,希望對大家有所幫助。歡迎參閱:Python生成數字圖片代碼分享、Python列表刪除的三種方法代碼分享、13個最常用的Python深度學習庫介紹等,有什么問題可以隨時留言,歡迎大家交流參考。

相關文章

最新評論