首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在python中使用异步或并发技术控制循环检测任务

在python中使用异步或并发技术控制循环检测任务
EN

Stack Overflow用户
提问于 2021-06-24 22:54:08
回答 1查看 31关注 0票数 0

我正在开发一个检测工具,我希望能够在网络上控制它。web服务应支持工具的启动和停止以及修改检测配置。但我不知道如何使服务和工具并行工作,因为检测工具不断地在检测过程中循环。

我有一些关于网络和异步的知识。但我知道的那些方法是“阻塞并等待所有可并行任务在结束时完成”,但我的探测任务应该在激活后不断执行,这让我感到困惑。

我已经写了一个小例子来说明这一点:

代码语言:javascript
复制
from typing import Optional, List

from fastapi import FastAPI, Query
from pydantic import BaseModel

config = {}
should_detecting = False
is_detecting = False
config_changed = False


def detect_task():
    global is_detecting
    global config_changed

    while should_detecting:
        is_detecting = True
        result = do_time_consuming_detect(config)
        if should_detecting and not config_changed:
            send(result)
        config_changed = False
    
    is_detecting = False


@app.get(root_route + "/detect")
def do_detect(start_flag: int):
    global should_detecting

    if start_flag == 1 and is_detecting != True:
        should_detecting = True
        execute_asynchronously(detect_task)
    elif start_flag == 0:
        should_detecting = False
    return {}

@app.get(root_route + "/update_config")
def update_config(new_config: dict):
    global config_changed
    
    config_changed = True
    config.update(new_config)
    return {}

所以我想知道如何使这个web服务与detect_task()并行工作。提前感谢您的帮助!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-06-26 19:10:02

我已经找到了答案。因为fastAPI提供了BackgroundTasks函数,所以您需要做的就是将任务放入其中。

代码语言:javascript
复制
def detect(flags, ips):
    flags['is_detecting'] = True
    while flags['should_detect']:
        do_some_detect()
    flags['is_detecting'] = False

@app.get(root_route + "/detect")
def read_detect(start_flag: int, background_tasks: BackgroundTasks):
    if start_flag == 1 and not flags['is_detecting']:
        flags['should_detect'] = True
        background_tasks.add_task(detect, flags, detecors)
    elif start_flag == 0:
        flags['should_detect'] = False
    return {}

标志和检测器只是作为参数传递到任务中的全局变量。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68118109

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档