1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
| import time
import threading
class Intervallometre(threading.Thread):
"""permet d'appeler une foncton toutes les x secondes
"""
def __init__(self, duree, fonction, args=[], kwargs={}):
threading.Thread.__init__(self)
# stocke les arguments donnés à l'appel
self.duree = duree
self.fonction = fonction
self.args = args
self.kwargs = kwargs
# pour permettre l'arrêt a la demande
self.encore = True
def run(self):
""" partie exécutée en tâche de fond
"""
while self.encore:
self.timer = threading.Timer(self.duree, self.fonction, self.args, self.kwargs)
self.timer.setDaemon(True)
self.timer.start()
self.timer.join() # on attend que le timer ait appelé la fonction
def stop(self):
""" méthode à appeler pour stopper l'intervallomètre
"""
self.encore = False # pour empêcher un nouveau lancement de Timer et terminer le thread
if self.timer.isAlive():
self.timer.cancel() # pour terminer une éventuelle attente en cours de Timer
def test(ch):
print(ch)
t = time.time()
intervallometre = Intervallometre(0.5, test, ["toto"])
intervallometre.start()
# on attend 10 secondes pendant lesquelles la fonction test s'exécute périodiquement
while time.time() - t <= 10:
pass
# on stoppe l'intervallometre
intervallometre.stop()
print("===> FIN") |
Partager