简体   繁体   中英

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.

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.

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

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

Try Multi Threading

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM