← 输入框|github.com|刷新
Skip to content

How to elegantly use result_backend.set_progress ?? #464

Closed

Description

@KitStarLee
@broker.task
async def heavy_task(key: str, val: str, context: Context = TaskiqDepends()) -> str:

    for i in range(10):
        # Simulate some work
        await asyncio.sleep(1)
        # Calculate progress
        progress = (i + 1) * 10
        # Send the progress
        # await context.set_progress(progress)

    await asyncio.sleep(10)

How to obtain the current task_id in the above code ?

Then set the progress using context.broker.result_backend.set_progress().

Because get_ progress returns None by default.

Activity

  1. s3rius commented on May 13, 2025

    @s3rius
    Member

    You can obtain the current task_id from context.message.task_id.

    Also, I'm not sure if Context has a method named set_progress. In order to set a progress, you need to depend on ProgressTracker.

  2. danfimov commented on Sep 17, 2026

    @danfimov
    Member

    Code example:

    import asyncio
    
    from taskiq import TaskiqDepends
    from taskiq.depends.progress_tracker import ProgressTracker, TaskState
    
    # broker = ... (not InMemoryBroker)
    
    @broker.task
    async def heavy_task(
        key: str,
        val: str,
        progress: ProgressTracker[str] = TaskiqDepends(),
    ) -> str:
        for i in range(10):
            await asyncio.sleep(1)
            pct = (i + 1) * 10
            await progress.set_progress(TaskState.STARTED, meta=f"{pct}%")
    
        return "done"

    You can read progress from other place (for example from http handler while task still working) by using task that you get from .kiq():

    task = await heavy_task.kiq("k", "v")
    
    # somewhere in other place
    progress = await task.get_progress()  # taskiq/task.py:106
    if progress is not None:
        print(progress.state, progress.meta)

    I will add part about set/get progress in documentation

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    questionFurther information is requested

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions