DEV Community

Hasan Sajedi
Hasan Sajedi

Posted on

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

Top comments (2)

Collapse
 
n_anselm profile image
n-anselm

Excellent! Thank you so much!

Collapse
 
udoyen profile image
george udosen

Oh what a Killer script to have, oshe!