DEV Community


Running a method as a background process in Python

Hasan Sajedi
・1 min read

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

Discussion (1)

udoyen profile image
george udosen

Oh what a Killer script to have, oshe!