python-trio / python-trio/trio
Is there any easy way to cancel task by some third-party event?
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:
- create new task, if no current task
- create other new task (concurrently) if specific event (currently not implemented)
- cancel current task, if there are some tasks
- stop
- 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
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- 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