user22341
user22341

Reputation: 83

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 and over.

what I want is to run this loop in the background so I don't block the rest of my code from executing.

Upvotes: 3

Views: 7077

Answers (4)

Tim
Tim

Reputation: 2637

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.

Upvotes: 6

seepalavardhan
seepalavardhan

Reputation: 49

Try Multi Threading

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

Upvotes: 0

Calder White
Calder White

Reputation: 1326

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()

Upvotes: 2

Syafiqur_
Syafiqur_

Reputation: 587

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()

Upvotes: 0

Related Questions