SoFunction
Updated on 2024-11-14

Detailed Python Multithreading Timer Timer/Delayed Execution, Event Events

Timer inherits from the sub-Thread class and is a subclass of Thread, which is also a thread class with the abilities and characteristics of a thread. This class is used to define how often to execute a function.

Its instances are threads that can delay the execution of the target function, and can cancel it until the target function is actually executed.

Timer source code:

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

Timer class to use the same way with the Thread definition of sub-threads, interval passed into the interval, function passed into the thread to execute the function, args and kwargs passed into the function of the parameters.

Early cancel:

import threading
import time
def add(x,y):
 print(x+y)
t = (10,add,args=(4,5))
()
(2)
()
print("===end===")

Run results:

===end===

After the start method is executed, the Timer object will be in a waiting state and will execute the add function after 10 seconds of waiting. Meanwhile, in the waiting phase before the execution of the add function, the main thread uses the cancel method of the child thread, it will skip the execution of the end of the function.

Implements the Timer timer using event events:

import threading
import logging
import time
(level=)
# class MyTimer():
class MyTimer:
 def __init__(self,interval,fn,args=None):
   = interval
   = fn
   = args
   = ()
 def start(self):
  (target=self.__do).start()
 def cancel(self):
  ()
 def __do(self):
  ()
  if not .is_set():
   (*)
def add(x,y):
 (x+y)
t = MyTimer(5,add,(4,5))
()
# (2)
# ()

Run results:

WARNING:root:9

Event events, the simplest implementation of the inter-thread communication mechanism, use an internal flag that is manipulated by a change in 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 set to True
-clear() flag set to False
-is_set() flag is True or not, return Boolean value
-wait(timeout=None) Set the time to wait for the flag to become True, None means infinite wait. If you wait, return True, if you don't wait, return False.

Examples:

The boss hires a worker to produce cups, and the boss waits for the worker until 10 cups have been produced.

import threading
import logging
import time
(level=)
cups = []
event = ()#event object
def boss(e:):
 if (30):#Wait up to 30 seconds
  ('Good job.')
def worker(n,e:):
 while True:
  (0.5)
  (1)
  ('make 1')
  if len(cups) >=n:
   ('I finished my job. {}'.format(len(cups)))
   ()#flag set to True
   break
b = (target=boss,name='boos',args=(event,))
w = (target=worker,args=(10,event))
()
()

Run results:

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. 10
INFO:root:Good job.

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

The boss wait() is set to wait for up to 30 seconds, the wait flag is changed to True, and when the worker has made enough 10 cups, the flag is set to True, and the worker must not have made a cup within 30 seconds.

The use of wait:

import threading
import logging
(level=)
def do(event:,interval:int):
 while not (interval): # not (1) = True
  ('To do sth.')
e = ()
t = (target=do,args=(e,1))
()
(10) # Can also be used (10)
()
print('Man Exit.')

Run results:

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 voluntarily gives up a time slice so that other threads can be scheduled, whereas sleep takes up a time slice and doesn't let it out.

Summary:

The Timer timer inherits from the Thread class, which is also a thread class. Its role is to wait for n seconds after the execution of a target function, you can use cancel to cancel early.

Event event is through True and False to maintain a flag flag value, through the value of this flag to decide to do something, wait () method can be set to wait for the longest flag is set to Ture the length of time, the timeout has not been set to True on the return to False.

PS: Here is a look at python's timer Timer

timer class

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

Construction Methods:

Timer(interval, function, args=[], kwargs={}) 
interval: appointed time 
function: Methods to be implemented 
args/kwargs: Parameters of the method

Instance Methods:

Timer is derived from Thread with no instance methods added.

Example one:

# encoding: UTF-8
import threading
def func():
  print 'hello timer!'
timer = (5, func)
()

The thread is delayed for 5 seconds before executing.

summarize

The above is a small introduction to the detailed Python multi-threaded Timer Timer/Delayed Execution, Event event, I hope to help you, if you have any questions please leave me a message, I will reply to you in a timely manner. I would also like to thank you very much for your support of my website!
If you find this article helpful, please feel free to reprint it, and please note the source, thank you!