Python timer instance code and python timer instance
In practical applications, we often need to use a timer to trigger some events. In Python, timer is implemented through threads, which is very simple to use. Example:
import threadingdef fun_timer(): print('Hello Timer!')timer = threading.Timer(1, fun_timer)timer.start()
Output result:
Hello Timer!Process finished with exit code 0
Note that the program is finished after only one output, which is obviously not the expected result. Refer to the explanatory description in the Timer class:
"""Call a function after a specified number of seconds"""
A function is called after a period of time, but it does not need to be called cyclically. Therefore, the modification is as follows:
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()
Output result:
Hello Timer!Hello Timer!Hello Timer!Hello Timer!............
The timer works properly.
Note the following four aspects when using the Python Timer:
(1) The timer constructor mainly has two parameters: the first parameter is time, and the second parameter is the function name, the first parameter indicates how long it will take to call the function specified by the second parameter. The second parameter is the function object, which is used for parameter passing. The function name (such as fun_timer) is used to represent the object. The function execution statement fun_timer () cannot be used. Otherwise, an error is returned. You can see the difference between the two by using type.
print(type(fun_timer()))print(type(fun_timer))
Output:
Hello Timer!<class 'NoneType'><class 'function'>
(2) The timer must be constructed repeatedly within the timer execution function, because the timer is only executed once after construction and must be called cyclically.
(3) The timer interval is measured in seconds. It can be a floating point number, such as 5.5 or 0.02. The values given inside and outside the execution function fun_timer can be different. In the preceding example, the first execution of fun_timer is one second, and the subsequent execution is 5.5 seconds later.
(4) You can use cancel to stop the timer, as shown in the following example:
#-*-Coding: UTF-8-*-import threadingimport timedef fun_timer (): print ('Hello Timer! ') Global timer = threading. timer (5.5, fun_timer) timer. start () timer = threading. timer (1, fun_timer) timer. start () time. sleep (15) # stop the timer after 15 seconds. cancel ()
Output:
Hello Timer!Hello Timer!Hello Timer!Process finished with exit code 0
The following is a Python write timer with adjustable timing precision.
#-* Coding: UTF-8-*-import sysimport osimport getoptimport threadingimport timedef Usage (): usage_str = ''' Description: \ t timer \ timer. py-h displays the help information. You can also use the -- help option \ timer. py-d num specifies a delay time (in milliseconds) \ t you can also use the -- duration = num option '''print (usage_str) def args_proc (argv ): '''process command line parameters ''' try: opts, args = getopt. getopt (sys. argv [1:], 'hd: ', ['help', 'duration =']) Doesn't getopt. getoptError as err: print ('error! Specify the correct command line parameters for the script. \ N') Usage () sys. exit (255) if len (opts) <1: print ('Usage prompt: required parameters are missing. ') 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 ('error! The specified parameter value % s is invalid. \ N' % (value) Usage () sys. exit (2) else: usr_argvs ['-d'] = int (value) else: print ('unhandled option') sys. exit (3) return usr_argvsdef timer_proc (interval_in_millisecond): loop_interval = 10 # timing precision, cycle interval (milliseconds), and interval for refreshing output information, it cannot be greater than the specified maximum latency, otherwise it may lead to no output t = interval_in_millisecond/loop_intervalwhile 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-= 1if millisecond! = 0: millisecond = 0 print ('\ rThe remaining time: % 02d: % 02d: % 03d... '% (min, sec, millisecond), end =' \ t \ t') print () # application portal 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
Summary
The above is all about the Python timer instance code in this article. I hope it will help you. For details, refer to: Python generation of digital image code sharing, Python list deletion of three methods of code sharing, 13 most commonly used Python Deep Learning Library introduction, etc. If you have any questions, please feel free to leave a message, you are welcome to exchange your reference.