Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run background tasks in python

I'm developing a small web service with Flask which needs to run background tasks, preferably from a task queue. However, after googling the subject the only results were essentially Celery and Redis Queue, which apparently require separate queuing services and thus are options that are far too heavy and convoluted to deploy. As all I'm looking for is a simple background task queue that enables tasks to be queued and executed on separate threads/processes, does anyone know if there is anything like this available in Python?

like image 635
RAM Avatar asked Jan 21 '20 23:01

RAM


People also ask

How do I run a code in the background?

Use bg to Send Running Commands to the Background You can easily send these commands to the background by hitting the Ctrl + Z keys and then using the bg command. Ctrl + Z stops the running process, and bg takes it to the background.

How do I open background tasks?

View tasks that are running in the background Choose Window > Background Tasks (or press Command-9). In the toolbar, click the Background Tasks button.

How do I run a background task in Django?

In Django Background Task, all tasks are implemented as functions (or any other callable). There are two parts to using background tasks: creating the task functions and registering them with the scheduler. setup a cron task (or long running process) to execute the tasks.


2 Answers

import threading
import time

class BackgroundTasks(threading.Thread):
    def run(self,*args,**kwargs):
        while True:
            print('Hello')
            time.sleep(1)

t = BackgroundTasks()
t.start()

After the while statement , you can put the code you want to run in background. Maybe deleting some models , sending email or whatever.

like image 115
Farhan Syedain Avatar answered Oct 25 '22 16:10

Farhan Syedain


The asyncio library might be what you are looking for

import asyncio

async def main():
    print('Hello ...')
    await asyncio.sleep(1)
    print('... World!')

# Python 3.7+
asyncio.run(main())
like image 32
user3919706 Avatar answered Oct 25 '22 15:10

user3919706