Home > other >  Background task with asyncio
Background task with asyncio

Time:01-27

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:

  1. 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)
  1. 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? Thanks

CodePudding user response:

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.run()
        t2 = threading.Thread(target=self.print_logs)

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

x = processMessages()
x.t2.run()
  • Related