首页 > 解决方案 > 在后台运行异步数据库读取任务

问题描述

我有一个函数get_active_allowed_systems_by_poll,我想在后台调用它 10 次/分钟,并刷新我在过去 10 秒内获得的新系统。

import asyncio
from threading import Thread


async def create_state_machine_at_init(app):

    worker_loop = asyncio.new_event_loop()
    worker = Thread(target=start_db_worker, args=(worker_loop,))
    worker.start()

    worker_loop.call_soon_threadsafe(get_active_allowed_systems_by_poll, app, 30)


async def get_active_allowed_systems_by_poll(app, interval=10):
    params = {
        param: key
        for param, key
        in app.config.get_active_allowed_systems_by_poll_params.items()
        }
    params['interval'] = interval

    operation = prepare_exec(
        app.config.get_active_allowed_systems_by_poll,
        **params
        )
    ACTIVE_ALLOWED_SYSTEMS
    ACTIVE_ALLOWED_SYSTEMS = (await app['database'].execute(operation)).all()
    return ACTIVE_ALLOWED_SYSTEMS

def start_db_worker(loop):
    """Switch to new event loop and run forever"""

    asyncio.set_event_loop(loop)
    loop.run_forever()

/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/asyncio/events.py:145:RuntimeWarning:协程'get_active_allowed_systems_by_poll'从未等待

标签: python-3.xpython-asynciopython-multithreading

解决方案


推荐阅读