Advertisement
adnan360

Python threading class example that ends with program.

Jan 6th, 2015
207
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.86 KB | None | 0 0
  1. # http://sebastiandahlgren.se/2014/06/27/running-a-method-as-a-background-thread-in-python/
  2.  
  3. import threading
  4. import time
  5.  
  6.  
  7. class ThreadingExample(object):
  8.     """ Threading example class
  9.     The run() method will be started and it will run in the background
  10.     until the application exits.
  11.     """
  12.      
  13.     def __init__(self, interval=1):
  14.         """ Constructor
  15.         :type interval: int
  16.         :param interval: Check interval, in seconds
  17.         """
  18.         self.interval = interval
  19.  
  20.         thread = threading.Thread(target=self.run, args=())
  21.         thread.daemon = True # Daemonize thread
  22.         thread.start() # Start the execution
  23.      
  24.     def run(self):
  25.         """ Method that runs forever """
  26.         while True:
  27.             # Do something
  28.             print('Doing something imporant in the background')
  29.              
  30.             time.sleep(self.interval)
  31.              
  32. example = ThreadingExample()
  33. time.sleep(3)
  34. print('Checkpoint')
  35. time.sleep(2)
  36. print('Bye')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement