python-trio / python-trio/trio

Is there any easy way to cancel task by some third-party event?

Open
#2,624 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
Python
Stars
7.3k
Forks
431
Avg merge
2d 17h
Merged PRs (30d)
6

Description

I have code in asyncio
The code just listening any messages via redis pub/sub, and need to:

  1. create new task, if no current task
  2. create other new task (concurrently) if specific event (currently not implemented)
  3. cancel current task, if there are some tasks
  4. stop
  5. quit
import asyncio
import signal
import sys
import redis.asyncio as redis
from functools import partial


STOPWORD = "STOP"
QUITWORD = "QUIT"

task = None
redis_pubsub_listener = None

async def my_task(string=None):
    counter = 0
    if string is None:
        string = 'task'
    if string == 'w':
        raise LookupError()
    while True:
        print(f'Running my {string} {counter}...')
        await asyncio.sleep(1)
        counter += 1
            
async def listen_for_input(channel: redis.client.PubSub):
    global task
    while True:
        message = await channel.get_message(ignore_subscribe_messages=True)
        if message is not None:
            print(f'{message=}')

            message_str = message["data"].decode()
            if task is not None:
                task.cancel()
            
            if message_str == QUITWORD:
                redis_pubsub_listener.cancel()
            elif message_str != STOPWORD:
                task = asyncio.create_task(my_task(message_str))
                
        await asyncio.sleep(0.01)
        
            
async def main():
    # Create a task
    global redis_pubsub_listener
    
    r = await redis.from_url("redis://localhost")
    async with r.pubsub() as pubsub:
        await pubsub.psubscribe("channel:*")
        redis_pubsub_listener = asyncio.create_task(listen_for_input(pubsub))
        
        while not redis_pubsub_listener.cancelled():
            try:
                if task is None:
                    await asyncio.gather(redis_pubsub_listener)
                else:
                    await asyncio.gather(task, redis_pubsub_listener)

            except asyncio.CancelledError:
                print('Task was cancelled')

if __name__ == '__main__':
    asyncio.run(main())

This code is doing thing, but it is not easy code, and uses global, and I very love trio

Can you help me find how to cancel and create tasks at some events in trio?

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the my_task, listen_for_input, and main entry points in the example, and compare the requested task-creation and cancellation flow with Trio's structured-concurrency model. Done would be a clear, documented answer showing how the third-party event, cancellation, stopping, and quitting requirements map to Trio.

Written by the indexing model from the issue text.

Assessment

Tech stack
python, redis
Domain
backend
Issue type
Documentation
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.