Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Example Analysis of Python multithreaded Timer timer / delayed execution and Event events

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly shows you the "Python multithreaded Timer timer / deferred execution, Event event example analysis", the content is easy to understand, well-organized, hope to help you solve your doubts, the following let Xiaobian lead you to study and learn "Python multithreaded Timer timer / deferred execution, Event event example analysis" this article.

Timer inherits the subclass Thread, which is a subclass of Thread and is also a threading class, which has the capabilities and characteristics of threading. This class is used to define how often a function is executed.

An example of it is a thread that can delay the execution of the target function, which can be cancel before the target function is actually executed.

Timer source code:

Class Timer (Thread): def _ init__ (self, interval, function, args=None, kwargs=None): Thread.__init__ (self) self.interval = interval self.function = function self.args = args if args is not None else [] self.kwargs = kwargs if kwargs is not None else {} self.finished = Event () def cancel (self): "" Stop the timer if it hasn't finished yet. "" Self.finished.set () def run (self): self.finished.wait (self.interval) if not self.finished.is_set (): self.function (* self.args, * * self.kwargs) self.finished.set ()

The Timer class uses the same method as Thread to define child threads: interval passes in the interval time, function passes in the function executed by the thread, and args and kwargs passes in the parameters of the function.

Cancel ahead of time:

Import threadingimport timedef add (x _ time.sleep): print (x _ ray) t = threading.Timer (10 _ () _

Running result:

= end===

After the start method executes, the Timer object waits, and the add function executes after waiting for 10 seconds. At the same time, during the wait phase before executing the add function, the main thread uses the cancel method of the child thread and skips the end of executing the function.

Use the event event to implement the Timer timer:

Import threadingimport loggingimport timelogging.basicConfig (level=logging.INFO) # class MyTimer (threading.Thread): class MyTimer: def _ init__ (self,interval,fn Args=None): self.interval = interval self.fn = fn self.args = args self.event = threading.Event () def start (self): threading.Thread (target=self.__do). Start () def cancel (self): self.event.set () def _ do (self): self.event.wait (self.interval) if not self.event.is_set (): self.fn (* self.args) def add (xjingy): logging.warning (xonomy) t = MyTimer (5dadd) (4) t.start () # time.sleep (2) # t.cancel ()

Running result:

WARNING:root:9

The Event event, the simplest implementation of the inter-thread communication mechanism, uses an internal tag flag to operate through changes in the True or False of the flag.

Event source code:

Class Event:

Def _ _ init__ (self): self._cond = Condition (Lock ()) self._flag = False def _ reset_internal_locks (self): self._cond.__init__ (Lock ()) def is_set (self): return self._flag isSet = is_set def set (self): with self._cond: self._flag = True self._cond.notify_all def clear (self): with self._cond: self._flag = False def wait (self Timeout=None): with self._cond: signaled = self._flag if not signaled: signaled = self._cond.wait (timeout) return signaled

Event method:

Set () flag is set to True

Clear () flag is set to False

Whether is_set () flag is True, which returns a Boolean value

Wait (timeout=None) sets the length of time to wait for flag to become True, while None waits indefinitely. When True is returned, False is returned before timeout.

For example:

The boss hired a worker to make cups, and the boss waited for the workers until ten cups were produced.

Import threadingimport loggingimport timelogging.basicConfig (level=logging.INFO) cups = [] event = threading.Event () # event object def boss (e:threading.Event): if e.wait (30): # wait up to 30 seconds logging.info ('Good job.') def worker: while True: time.sleep (0.5) cups.append (1) logging.info (' make 1') if len (cups) > = n: logging.info ('I finished my job. {} '.format (len (cups)) e.set () # flag is set to True breakb = threading.Thread (target=boss,name='boos',args= (event,)) w = threading.Thread (target=worker,args= (10heroine event)) w.start () b.start ()

Running result:

INFO:root:make 1

INFO:root:make 1

INFO:root:make 1

INFO:root:make 1

INFO:root:make 1

INFO:root:make 1

INFO:root:make 1

INFO:root:make 1

INFO:root:make 1

INFO:root:make 1

INFO:root:I finished my job. ten

INFO:root:Good job.

The boss and worker use the tag flag of the same Event object.

The boss wait () is set to wait up to 30 seconds for flag to become True. When the worker makes 10 cups, the flag is set to True. The worker must not make the cup within 30 seconds.

Use of wait:

Import threadingimport logginglogging.basicConfig (level=logging.INFO) def do (event:threading.Event,interval:int): while not event.wait (interval): # not event.wait (1) = True logging.info ('To do sth.') e = threading.Event () t = threading.Thread (target=do,args= (eMagol 1)) t.start () e.wait (10) # you can also use time.sleep (10) e.set () print ('Man Exit.')

Running result:

INFO:root:To do sth.

INFO:root:To do sth.

INFO:root:To do sth.

INFO:root:To do sth.

INFO:root:To do sth.

INFO:root:To do sth.

INFO:root:To do sth.

INFO:root:To do sth.

INFO:root:To do sth.

Man Exit.

The difference between wait and sleep is that wait will actively give up time slices, other threads can be scheduled, and sleep will occupy time slices.

Summary:

Timer timers inherit from the Thread class, which is also a thread class. Its function is to wait n seconds before executing an objective function, which can be canceled in advance using cancel.

The Event event maintains a flag tag value through True and False, and the value of this tag determines to do something. The wait () method sets the maximum length of time to wait for flag to be set to Ture, and returns False before the timeout is set to True.

PS: let's take a look at python's timer Timer

Timer class

Timer (timer) is a derived class of Thread that is used to call a method after a specified time.

Construction method:

Timer (interval, function, args= [], kwargs= {}) interval: specified time function: method to be executed args/kwargs: parameters of the method

Example method:

Timer derives from Thread and does not add instance methods.

Example 1:

# encoding: UTF-8import threadingdef func (): print 'hello timers timer = threading.Timer (5, func) timer.start ()

The thread executes after a delay of 5 seconds.

These are all the contents of the article "Python multithreaded Timer timer / delayed execution, sample Analysis of Event events". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report