Rishi
Rishi

Reputation: 37

Multithreading in Python without using time.sleep at the end?

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')

Upvotes: 1

Views: 804

Answers (2)

Yoav Glazner
Yoav Glazner

Reputation: 8066

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...

Upvotes: 2

cadrian
cadrian

Reputation: 7376

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.

Upvotes: 2

Related Questions