How to asynchronously create and cancel a task?

  asynchronous, python, python-asyncio

I am quite new to async in python and I can see it has a lot of different options, but they arent that well documented in my opinion.

I’m creating a framework that uses 2 threads/processes, 1 for handling/parsing commands and the other one for executing commands. I’m not yet 100% confirmed about it but I think I will let the two threads/processes talk via a Pipe. Next is a picture for more clarity:
explanation picture

Now, I already have thread 1 done and working, but thread 2 has been bugging me for a while now. I’m quite new to async in python and I can’t seem to get what i want despite searching online alot. I want to be able to asynchronously (non-blocking) create and run a task in the threads’ loop. And also cancel/remove that tatsk (asynchronously). I have tried multiple things but couldnt get anything working. If someone can help me with some proof of concept code that would mean a lot to me, below is some boilerplate code that you could maybe use:

async def test_task(url, *args):
    async with aiohttp.ClientSession() as s:
        while True:
            resp = await s.get(url)
            print(resp)
            asyncio.sleep(2)


class Thread2:

    async def create_task(self):

        # asynchronously add a task to the running event and run it

        pass

    async def cancel_task(self):

        # asynchronously cancel a task from the running event

        pass

Im just looking for a small POC. If anyone could I would be delighted. Thanks.

Source: Python Questions

LEAVE A COMMENT