Skip to content

Fix/371 repeat every task lifecycle#372

Open
Binilkks wants to merge 2 commits intofastapiutils:masterfrom
Binilkks:fix/371-repeat-every-task-lifecycle
Open

Fix/371 repeat every task lifecycle#372
Binilkks wants to merge 2 commits intofastapiutils:masterfrom
Binilkks:fix/371-repeat-every-task-lifecycle

Conversation

@Binilkks
Copy link
Copy Markdown

@Binilkks Binilkks commented Apr 9, 2026

Summary

This PR addresses issue #371 by improving lifecycle management for repeated background tasks created by repeat_every.

Previously, repeat_every started tasks in the background without exposing a task handle, which made it hard to inspect or cancel running tasks during shutdown/reload scenarios.

What Changed

  • Switched task creation from ensure_future to create_task in fastapi_utils/tasks.py.
  • Added internal tracking of active repeated tasks using a weak-reference registry in fastapi_utils/tasks.py.
  • Added new helper API:
    • get_repeated_task(task_func): returns the active task handle (or None)
    • cancel_repeated_task(task_func): cancels active task and returns success status
  • Added done-callback cleanup so completed tasks are removed from the internal registry.
  • Added tests for sync and async paths to verify task handle visibility and cancellation behavior in tests/test_tasks.py.

Why

This provides a safer lifecycle path for long-running services:

  • Inspect running repeated tasks
  • Cancel repeated tasks explicitly
  • Reduce orphan/background task management risk

Behavior Impact

  • Existing repeat_every usage remains compatible.
  • New lifecycle helpers are additive and optional.
  • Task execution behavior (seconds, wait_first, max_repetitions, on_exception, on_complete) is unchanged.

Testing

  • Added new unit tests in tests/test_tasks.py for:
    • task handle retrieval
    • task cancellation (sync and async function variants)
  • Note: local test execution in current environment reported missing async pytest plugin setup, so full runtime verification should be done in CI/project test environment.

Related

Closes #371

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[BUG] Repeated background task has no lifecycle handle/cancel path (orphan task risk)

1 participant