簡體   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