将对象与asyncio和线程组合

时间:2018-11-13 06:48:24

标签: python multithreading object asynchronous

我正在尝试将线程和asyncio组合在一起,以在我的非异步代码中包含async模块。我是对象和asyncio的初学者,因此欢迎您提供帮助。

import threading
import asyncio

class WatchdogManager(threading.Thread):

    def __init__(self):
        self.loop = asyncio.get_event_loop()
        threading.Thread.__init__(self, target=self.loop_in_thread, args=(self.loop,))

    def run(self):
        self.watchdog_manager()

    def loop_in_thread(self):
        asyncio.set_event_loop(self)
        self.loop.run_until_complete(self.watchdog_manager())

    async def watchdog_manager(self):
        print("watchdog manager initiated")
        while True:
            print("watchdog manager running")
            await asyncio.sleep(5)


watchdog_manager = WatchdogManager()
watchdog_manager.start()

print("we can continue without being blocked")

我得到一个错误:

  

协程从未等待

我基本上是想将以下代码变成一个对象:

import asyncio
import threading


async def greet_every_two_seconds():
    while True:
        print('Hello World')
        await asyncio.sleep(5)

def loop_in_thread(loop):
    asyncio.set_event_loop(loop)
    loop.run_until_complete(greet_every_two_seconds())


loop = asyncio.get_event_loop()


t = threading.Thread(target=loop_in_thread, args=(loop,))
t.start()

print("we can continue without being blocked")

1 个答案:

答案 0 :(得分:0)

import threading
import asyncio

class WatchdogManager (threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self,target=self.loop_in_thread, args=(self.loop,))

    async def watchdog_manager(self):
        print("Watchdog manager initiated")
        while True:
            print("Watchdog manager running")
            await asyncio.sleep(5)

def loop_in_thread(self,loop):
    asyncio.set_event_loop(loop)
    loop.run_until_complete(self.Watchdog_manager())

loop = asyncio.get_event_loop()

Run it:

watchdog_manager= WatchdogManager(app_log)
watchdog_manager.start()