Running a method as a background process in Python

hasansajedi

Hasan Sajedi

Posted on August 20, 2018

Running a method as a background process in Python

Below a little code snippet for running class methods as background threads in Python. The run() method does some work forever and in this use case you want it to do that in the background. while the rest of the application continues it’s work.

import time

import threading


class TestThreading(object):
    def __init__(self, interval=1):
        self.interval = interval

        thread = threading.Thread(target=self.run, args=())
        thread.daemon = True
        thread.start()

    def run(self):
        while True:
            # More statements comes here
            print(datetime.datetime.now().__str__() + ' : Start task in the background')

            time.sleep(self.interval)

tr = TestThreading()
time.sleep(1)
print(datetime.datetime.now().__str__() + ' : First output')
time.sleep(2)
print(datetime.datetime.now().__str__() + ' : Second output')

Below is Output:

2018-08-18 13:39:59.021000 : Start task in the background
2018-08-18 13:40:00.036000 : First output
2018-08-18 13:40:00.036000 : Start task in the background
2018-08-18 13:40:01.036000 : Start task in the background
2018-08-18 13:40:02.036000 : Second output

💖 💪 🙅 🚩
hasansajedi
Hasan Sajedi

Posted on August 20, 2018

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related