DEV Community

Hasan Sajedi
Hasan Sajedi

Posted on

10 3

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

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read more

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!

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more