Skip to content Skip to sidebar Skip to footer

How Do I Run An Infinite Loop In The Background?

I have a function that continuously monitors an API. Basically, the function gets the data, parses it then appends it to a file. then it waits for 15 minutes and does the same over

Solution 1:

If you are using asyncio (I assume you are due to the asyncio tag) a scheduled operation can be performed using a task.

import asyncio

loop = asyncio.get_event_loop()

async def check_api():
    while True:
        # Do API check, helps if this is using async methods
        await asyncio.sleep(15 * 60)  # 15 minutes (in seconds)

loop.create_task(check_api())

...  # Rest of your application

loop.run_forever()

If your API check is not async (or the library you are using to interact with it does is not async) you can use an Executor to run the operation in a separate thread or process while still maintaining the asyncio API.

For example:

from concurrent.futures import ThreadPoolExecutor

executor = ThreadPoolExecutor()

def call_api():
    ...

async def check_api():
    while True:
        await loop.run_in_executor(executor, call_api)
        await asyncio.sleep(15 * 60)  # 15 minutes (in seconds)

Note that asyncio does not automatically make your code parallel, it is co-operative multitasking, all of your methods need to cooperate by using await, a long-running operation will still block other threads and in that case, an Executor will help.


Solution 2:

This is very broad, but you could take a look at the multiprocessing or threading python modules.

For running a thread in the background it would look something like this:

from threading import Thread

def background_task():
    # your code here

t = Thread(target=background_task)
t.start()


Solution 3:

Try multithreading :

import threading

def background():
    while True:
        number = int(len(oilrigs)) * 49
        number += money
        time.sleep(1)

def foreground():
    // What you want to run in the foreground

b = threading.Thread(name='background', target=background)
f = threading.Thread(name='foreground', target=foreground)

b.start()
f.start()

Solution 4:

Try Multi Threading

import threading
def background():
    #The loop you want to run in back ground
b = threading.Thread(target=background)
b.start()

Post a Comment for "How Do I Run An Infinite Loop In The Background?"