0

I am trying to combine threads and asyncio to include an async module in my otherwise non-async code. I am a beginner in both objects and asyncio, so any help is welcome.

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

I get a error:

coroutine was never awaited

I am basically trying to turn the following code into an object:

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")
HCLivess
  • 1,015
  • 1
  • 13
  • 21

1 Answers1

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()
HCLivess
  • 1,015
  • 1
  • 13
  • 21