Background task with asyncio

Question:

I have one class produceMessages that keeps feeding messages to its attribute message_logs.
I want to process these messages in the other class processMessages. However, the code in processMessages won’t execute until produceMessages is done – which is never, as I want these messages to come forever.

Looking at documentation, I’ve found that the library asyncio might help me but I’m struggling to get the below example work:

This is first_file.py:

import asyncio
import random

class produceMessages:
    def __init__(self, timeout = 10):
        self.timeout = timeout
        self.message_logs = []

    async def run(self):
        while(True):
            self.message_logs.append(random.uniform(0, 1))           
            await asyncio.sleep(self.timeout)

This is second_file.py:

import first_file
import asyncio
import time

class processMessages:
    def __init__(self):
        self.producer = first_file.produceMessages()
        asyncio.run(self.producer.run())

    def print_logs(self):
        print(self.producer.message_logs)
        time.sleep(1)

x = processMessages()
x.print_logs()

How can I make this work?

Asked By: medihde

||

Answers:

I would recommend you try the library threading. This is how I would approach it with that:

import first_file
import asyncio
import time


class processMessages():
    def __init__(self):
        self.test = first_file.produceMessages()
        t = threading.Thread(target=self.test.run)
        t.start()
        t2 = threading.Thread(target=self.print_logs)

    def print_logs(self):
        print(self.test.message_logs)
        time.sleep(1)

x = processMessages()
x.t2.start()
Answered By: Eyal B
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.