Ce que cet article vous apporte, c'est une introduction à la méthode d'implémentation d'un minuteur de boucle en python (avec du code). J'espère qu'il a une certaine valeur de référence. vous sera utile.
Comment écrire un timer en python pour effectuer une certaine opération en boucle ?
Objet Timer
from threading import Timer def hello(): print "hello, world" t = Timer(10.0, hello) t.start()
Sortie après 10 secondes :
hello, world
Focus sur le code t = Timer(10.0, bonjour), python fournit un objet Timer, qui effectuera une opération après un temps spécifié ; sa forme complète :
class threading.Timer(interval, function, args=[], kwargs={})
interval est l'intervalle de temps, la fonction est un objet appelable, args et kwargs seront utilisés comme paramètres de fonction.
Remarque : la fonction ne sera exécutée qu'une seule fois et ne sera pas exécutée régulièrement, et Timer créera un nouveau thread lors de l'exécution de l'opération.
Il y a une légère différence entre Timer en python2 et python3 :
# python2.7 def Timer(*args, **kwargs): return _Timer(*args, **kwargs) # python3.7 class Timer(Thread): pass
En python3, Timer est une sous-classe de Thread en python2, _Timer est une sous-classe de Thread et Timer est ; juste une usine de la méthode de classe _Timer.
Le code ci-dessus n'imprimera hello, world qu'une seule fois, puis quittera. Alors, comment imprimer à intervalles réguliers en boucle ?
Minuterie de boucle approximative
Une façon consiste à continuer à enregistrer une minuterie dans la fonction, afin que la fonction puisse continuer à être exécutée dans l'intervalle suivant
from threading import Timer def hello(): print "hello, world" Timer(10.0, hello) .start() t = Timer(10.0, hello) t.start()
Il n'est donc pas recommandé de continuer à enregistrer un Timer dans la fonction.
from threading import _Timer def hello(): print "hello, world" class RepeatingTimer(_Timer): def run(self): while not self.finished.is_set(): self.function(*self.args, **self.kwargs) self.finished.wait(self.interval) t = RepeatingTimer(10.0, hello) t.start()
from threading import Thread def hello(): print "hello, world" # 继承 Thread class MyThread(Thread): # 把要执行的代码写到run函数里面 线程在创建后会直接运行run函数 def run(self): hello() t = MyThread() t.start()
class threading.Thread(group=None, target=None, name=None, args=(), kwargs={})
class Thread(_Verbose): def run(self): try: if self.__target: self.__target(*self.__args, **self.__kwargs) finally: # Avoid a refcycle if the thread is running a function with # an argument that has a member that points to the thread. del self.__target, self.__args, self.__kwargs
class _Timer(Thread): """Call a function after a specified number of seconds: t = Timer(30.0, f, args=[], kwargs={}) t.start() t.cancel() # stop the timer's action if it's still waiting """ def __init__(self, interval, function, args=[], kwargs={}): Thread.__init__(self) self.interval = interval self.function = function self.args = args self.kwargs = kwargs 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()
Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!