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(, args=())
        thread.daemon = True

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


tr = TestThreading()
print( + ' : First output')
print( + ' : 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)

n_anselm profile image

Excellent! Thank you so much!

udoyen profile image
george udosen

Oh what a Killer script to have, oshe!

50 CLI Tools You Can't Live Without

>> Check out this classic DEV post <<