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 50 51 52
| #!/usr/bin/python3
# -*- coding: utf-8 -*-
import time
import threading
##############################################################################
def affiche(texte):
print(texte)
##############################################################################
class Intervalle(threading.Thread):
#=========================================================================
def __init__(self, tempo, fonction, args=[], kwargs={}):
super().__init__()
self.tempo = tempo
self.fonction = fonction
self.args = args
self.kwargs = kwargs
self.encore = True # pour permettre l'arret a la demande
self.timer = None
#=========================================================================
def run(self):
"""partie qui s'exécute en tâche de fond
"""
while self.encore:
self.timer = threading.Timer(self.tempo, self.fonction, self.args, self.kwargs)
self.timer.setDaemon(True)
self.timer.start()
self.timer.join()
#=========================================================================
def stop(self):
""" empeche un nouveau lancement de la fonction et termine le thread
"""
self.encore = False
##############################################################################
if __name__ == '__main__':
intervalle = Intervalle(1, affiche, ["toto"])
intervalle.setDaemon(True)
intervalle.start()
#interval.join() # attente bloquante de l'arrêt du thread
time.sleep(10) # attendre 10s pendant lesquelles la fonction est appelée
intervalle.stop() # demande l'arrêt du thread |
Partager