Objective record
1 threading.Timer
1.1 threading.Timer structure
1.1.1 threading.Timer Constructors
1.1.2 parameter list
1.2 threading.Timer Properties and methods
1.3 threading.Timer Use demonstration
1.3.1 Simple deferred call
1.3.2 Call as a timer
1.3.3 The advantage of loop calling over starting a batch of threads at the same time
Python Multithreaded programming Directory
Python Multithreaded programming -01-threading The module first
Python Multithreaded programming -02-threading modular - Use of locks
Python Multithreaded programming -03-threading modular - Condition
Python Multithreaded programming -04-threading modular - Event
Python Multithreaded programming -05-threading modular - Semaphore and BoundedSemaphore
threading.Timer yes threading.Thread A derived class of , At the appointed time n Execute a function function in seconds . It will integrate threading.Thread Many properties and methods of .
Timer The source code implementation of is very simple , After receiving a task , Creates a thread , The thread logic is inserted at the front sleep. If you think about it , When there are many tasks , Context switching is also a resource consuming thing , You don't have to .
timer=threading.Timer(interval, function, args=None, kwargs=None)
Basically threading.Thread Properties and methods of , threading.Timer There are , Please refer to the previous article for details Python Multithreaded programming -01-threading The module first 2.1.1 Section .
besides , It also has some special methods .
Another one threading.Timer object , If the .finished() Method , Is to get a threading.Event Class object .
Here is a piece of code , I hope to print out in turn words In the list word, The delay time per thread depends on word The length of , And every time you print word Print the current time before .
import threading
import time
words=["a","12"," Hello !"," The spring breeze miles "]
timer_list=[]
def show_time_on_word(word):
print(time.ctime()+"==>"+word)
for word in words:
timer=threading.Timer(len(word)*10,show_time_on_word,args=[word])
timer_list.append(timer)
for timer in timer_list:
timer.start()
The operation results are as follows :
Want to run a piece of code , every other 10 Second time reporting , Cumulative time reporting 10 Time .
import threading
import time
count=0
def show_time():
print("Coming in show time!")
global count
if(count<10):
count+=1
print(time.ctime())
create_timer()
else:
print("All done!")
def create_timer():
timer=threading.Timer(10,show_time)
timer.start()
print(time.ctime()," Starting !")
create_timer()
Running results
1.3.2 It is mainly generated by circular call Timer, and 1.3.1 Is to generate a batch of threads at the same time . By comparison , Loop calls are better , By calling threading.active_count() It can be seen that , There is no need for multiple maintenance threads .