Python threading.timer - repeat function every 'n' seconds

前端 未结 13 1403
挽巷
挽巷 2020-11-22 09:45

I want to fire off a function every 0.5 seconds and be able to start and stop and reset the timer. I\'m not too knowledgeable of how Python threads work and am having diffic

13条回答
  •  余生分开走
    2020-11-22 10:30

    I have come up with another solution with SingleTon class. Please tell me if any memory leakage is here.

    import time,threading
    
    class Singleton:
      __instance = None
      sleepTime = 1
      executeThread = False
    
      def __init__(self):
         if Singleton.__instance != None:
            raise Exception("This class is a singleton!")
         else:
            Singleton.__instance = self
    
      @staticmethod
      def getInstance():
         if Singleton.__instance == None:
            Singleton()
         return Singleton.__instance
    
    
      def startThread(self):
         self.executeThread = True
         self.threadNew = threading.Thread(target=self.foo_target)
         self.threadNew.start()
         print('doing other things...')
    
    
      def stopThread(self):
         print("Killing Thread ")
         self.executeThread = False
         self.threadNew.join()
         print(self.threadNew)
    
    
      def foo(self):
         print("Hello in " + str(self.sleepTime) + " seconds")
    
    
      def foo_target(self):
         while self.executeThread:
            self.foo()
            print(self.threadNew)
            time.sleep(self.sleepTime)
    
            if not self.executeThread:
               break
    
    
    sClass = Singleton()
    sClass.startThread()
    time.sleep(5)
    sClass.getInstance().stopThread()
    
    sClass.getInstance().sleepTime = 2
    sClass.startThread()
    

提交回复
热议问题