Skip to content

gevent Timer.cancel() fails to stop recurring callbacks after the first tick #11028

Closed

Description

@IsaacsonMango

Description

When using Celery's gevent pool (-P gevent), cancelling a periodic timer created by Timer.call_repeatedly() fails once the first callback has completed.

The timer handle returned by call_repeatedly() is the first spawned _Greenlet, while subsequent ticks reuse the same underlying Kombu Entry. Because _Greenlet.cancel is aliased to Greenlet.kill, cancelling the handle after the first tick only kills the already-finished first greenlet without setting entry.canceled = True, so the next scheduled greenlet runs and keeps rescheduling indefinitely.

A related issue exists in Timer.clear(): if a repeating callback is currently running when clear() is called, killing the greenlet without marking g.entry.cancel() first allows the finally block in call_repeatedly() to schedule another iteration.

We ran into this on long-running celery -P gevent workers (Celery 5.6.2, Kombu 5.6.2, gevent 25.4.1, Python 3.10, Redis broker), where old Heart and Gossip timers kept firing every 2s after broker reconnects (related to #10273 / #10280).

Minimal Reproduction

Reproduced on main (tested with gevent 25.4.1 and 26.9.0; reproduction script by @MehrazRumman in #11015):

from gevent import monkey; monkey.patch_all()
import gevent
from celery.concurrency.gevent import Timer

timer = Timer()
ticks = []
handle = timer.call_repeatedly(0.05, lambda: ticks.append(1))
gevent.sleep(0.18)  # wait a few ticks so the first greenlet has finished
before = len(ticks)
timer.cancel(handle)
gevent.sleep(0.3)
print(len(ticks) - before, handle.entry.canceled)

Expected Behavior

The timer stops firing after timer.cancel(handle) and the underlying Entry is marked as cancelled:

0 True

Actual Behavior

The timer continues firing after cancellation and handle.entry.canceled remains False. One observed output on main:

6 False

(The exact number of extra ticks may vary slightly with scheduling.)

Related Issues and PR

Activity

  1. added this to the 5.7.x milestone on Nov 7, 2026
  2. zongsm-cmyk commented on Nov 7, 2026

    @zongsm-cmyk

    Root-Cause Analysis: Handle Desync in Recurring Gevent Timer Loops

    In Celery's gevent scheduling backend, Timer.call_repeatedly() returns a static reference to the initial greenlet instance (_Greenlet handle).

    However, during execution:

    1. When the initial callback iteration completes, recurring scheduling re-arms the timer via gevent.spawn_later or internal heap re-insertion.
    2. The outer handle returned to the caller (handle) maintains the reference to the original greenlet, which has already exited (dead=True).
    3. Calling handle.cancel() therefore executes against an already terminated greenlet, leaving subsequent rescheduled ticks active in the gevent hub event loop.

    Targeted Remediation

    Encapsulate recurring tasks in an atomic CancellablePeriodicEntry class that maintains a mutable reference to the active greenlet and an explicit cancellation flag:

    class RecurringGeventHandle:
        def __init__(self, timer, secs, entry, args=(), kwargs=None):
            self.timer = timer
            self.secs = secs
            self.entry = entry
            self.args = args
            self.kwargs = kwargs or {}
            self.cancelled = False
            self._current_g = None
            self._arm()
    
        def _arm(self):
            if not self.cancelled:
                import gevent
                self._current_g = gevent.spawn_later(self.secs, self._step)
    
        def _step(self):
            if self.cancelled:
                return
            try:
                self.entry(*self.args, **self.kwargs)
            finally:
                if not self.cancelled:
                    self._arm()
    
        def cancel(self):
            self.cancelled = True
            if self._current_g and not self._current_g.dead:
                self._current_g.kill(block=False)

    Reference & Benchmark

    For architecture patterns addressing non-blocking timer loops, connection queue buffers, and clean cancellation under I/O pressure:
    👉 https://github.com/zongsm-cmyk/llm-reliability-rescue-demo/blob/main/docs/benchmarks/zero_loss_webhook_ingestion_engine.md

  3. auvipy commented on Nov 7, 2026

    @auvipy
    Member

    @zongsm-cmyk we already have an open pr to fix this here #11015. instead of reviewing it to improve, i am not sure what you spammy comment adds here?

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

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions