1

So I'm trying to get some code running in the background using this snippet I found online. My main problem however is that I'm trying to get it to work without using the time.sleep(3) at the very end and can't seem to figure it out. Any suggestions? Why does it only work with time.sleep(n) at the end?

import threading
import time


class ThreadingExample(object):
    """ Threading example class
    The run() method will be started and it will run in the background
    until the application exits.
    """

    def __init__(self, interval=1):
        """ Constructor
        :type interval: int
        :param interval: Check interval, in seconds
        """
        self.interval = interval

        thread = threading.Thread(target=self.run, args=())
        thread.daemon = True                            # Daemonize thread
        thread.start()                                  # Start the execution

    def run(self):
        """ Method that runs forever """
        while True:
            # Do something
            print('Doing something imporant in the background')

            time.sleep(self.interval)

example = ThreadingExample()
time.sleep(3)
print('Done')
Rishi
  • 37
  • 1
  • 3
  • Looks like you want to be joining. Related: http://stackoverflow.com/questions/15085348/what-is-the-use-of-join-in-python-threading – SBI Jan 05 '16 at 10:12
  • 1
    Please read some basics about multithreading with Python. Eg.: http://www.tutorialspoint.com/python/python_multithreading.htm – kotlet schabowy Jan 05 '16 at 10:14

2 Answers2

2

You see this line

thread.daemon = True                            # Daemonize thread

It means that your thread will exit when the program ends(main thread). and if you don't put a

time.sleep(3)

Your program will exit so fast that the thread will most likely do nothing before exiting...

Yoav Glazner
  • 7,936
  • 1
  • 19
  • 36
2

When python exits, all the daemon threads are killed. If you exit too early, the thread that does the important background job will be killed befaore actually running.

Now your background job uses a while True; maybe you want to replace that with some actual exit condition, and join the thread before exiting.

cadrian
  • 7,332
  • 2
  • 33
  • 42