繁体   English   中英

如何在后台运行无限循环?

[英]How do I run an infinite loop in the background?

我有一个连续监视API的功能。 基本上,该函数获取数据,对其进行解析,然后将其附加到文件中。 然后等待15分钟,然后反复进行相同的操作。

我想要的是在后台运行此循环,这样我就不会阻止其余代码的执行。

如果您正在使用asyncio(我想您是由于asyncio标签所致),则可以使用任务执行计划的操作。

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

如果您的API检查不是异步的(或者您用来与之交互的库不是异步的),则可以使用执行程序在单独的线程或进程中运行该操作,同时仍保持异步API。

例如:

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)

请注意,asyncio不会自动使您的代码并行化,它是协作式多任务处理,您的所有方法都需要使用await进行协作,长时间运行的操作仍会阻塞其他线程,在这种情况下,执行器将提供帮助。

尝试多线程:

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

这非常广泛,但是您可以看一下多处理线程化 python模块。

为了在后台运行线程,它看起来像这样:

from threading import Thread

def background_task():
    # your code here

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

尝试多线程

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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