Skip to content

scheduler

Thread-safe priority-queue based event scheduler.

This module provides :class:Scheduler, a sched-like class that executes actions at scheduled times using a background thread and an executor. Events can be scheduled at absolute or relative times, cancelled by event or reference, and queried by predicate. A process-wide :func:common_scheduler is also provided.

Scheduler

A thread-safe event scheduler executing actions via an executor.

Events are stored in a heap ordered by (time, sequence). A daemon thread pops due events and submits them for execution.

Attributes:

Name Type Description
timegen

The time source used for now() and wait().

executor

The executor used to run scheduled actions.

Example
import py_misc_utils.scheduler as sch

s = sch.Scheduler()
ev = s.enter(0.01, lambda: None)
s.enterabs(s.timegen.now() + 0.02, lambda: None, ref='demo')
assert s.get_events(lambda e: e.ref == 'demo')
assert s.ref_cancel('demo')
assert s.cancel(ev)
Source code in py_misc_utils/scheduler.py
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
class Scheduler:
  """A thread-safe event scheduler executing actions via an executor.

  Events are stored in a heap ordered by (time, sequence). A daemon thread
  pops due events and submits them for execution.

  Attributes:
    timegen: The time source used for now() and wait().
    executor: The executor used to run scheduled actions.

  Example:
    import py_misc_utils.scheduler as sch

    s = sch.Scheduler()
    ev = s.enter(0.01, lambda: None)
    s.enterabs(s.timegen.now() + 0.02, lambda: None, ref='demo')
    assert s.get_events(lambda e: e.ref == 'demo')
    assert s.ref_cancel('demo')
    assert s.cancel(ev)
  """

  def __init__(self, timegen=None, executor=None, max_workers=None, name='Scheduler'):
    """Initialize the Scheduler with a time source and executor.

    Args:
      timegen: Optional time source; defaults to a TimeGen created with name.
      executor: Optional executor for running actions; defaults to a new
        Executor with max_workers.
      max_workers: Maximum number of executor workers if executor not provided.
      name: Name used for the scheduler thread and executor.
    """
    self._queue = []
    self._sequence = 0
    self._lock = threading.Lock()
    self._cond = threading.Condition(lock=self._lock)
    self.timegen = tg.TimeGen() if timegen is None else timegen

    if executor is not None:
      self.executor = executor
    else:
      executor = xe.Executor(max_threads=max_workers, name_prefix=name)
      fw.fin_wrap(self, 'executor', executor, finfn=executor.shutdown)

    self._runner = threading.Thread(target=self._run, daemon=True)
    self._runner.start()

  def _run_event(self, event):
    """Execute a scheduled event's action, logging exceptions.

    Args:
      event: The Event instance to execute.
    """
    try:
      event.action(*event.argument, **event.kwargs)
    except Exception as ex:  # noqa: BLE001 -- action isolation: user-scheduled actions must not kill the scheduler worker; failure is logged
      alog.exception(ex, exmsg='Exception while running scheduled action')

  def _run(self):
    """Main scheduler loop: wait for due events and submit them for execution."""
    while True:
      now, event = self.timegen.now(), None
      with self._lock:
        timeout = (self._queue[0].time - now) if self._queue else None
        if timeout is None or timeout > 0:
          self.timegen.wait(self._cond, timeout=timeout)
        else:
          event = heapq.heappop(self._queue)

      if event is not None:
        self.executor.submit(self._run_event, event)

  def gen_unique_ref(self):
    """Generate a unique reference string for event cancellation.

    Returns:
      A UUID4-based string.
    """
    return str(uuid.uuid4())

  def enterabs(self, ts, action, ref=None, argument=(), kwargs=None):
    """Schedule an action at an absolute timestamp.

    The timestamp is interpreted in the time source of the scheduler
    (timegen), which by default is the wall clock.

    Args:
      ts: The absolute time to run the action.
      action: The callable to execute.
      ref: Optional reference identifier for later cancellation.
      argument: Positional arguments for action.
      kwargs: Keyword arguments for action.

    Returns:
      The scheduled Event instance.
    """
    with self._lock:
      event = Event(time=ts,
                    sequence=self._sequence,
                    ref=ref,
                    action=action,
                    argument=argument,
                    kwargs=kwargs or {})
      self._sequence += 1

      heapq.heappush(self._queue, event)
      # Notify the scheduler thread only if the new event became the
      # closest-deadline one - otherwise it would just wake up for nothing.
      if id(event) == id(self._queue[0]):
        self._cond.notify()

    return event

  def enter(self, delay, action, ref=None, argument=(), kwargs=None):
    """Schedule an action after a relative delay.

    Args:
      delay: Seconds from now to run the action.
      action: The callable to execute.
      ref: Optional reference identifier for later cancellation.
      argument: Positional arguments for action.
      kwargs: Keyword arguments for action.

    Returns:
      The scheduled Event instance.
    """
    return self.enterabs(self.timegen.now() + delay,
                         action,
                         ref=ref,
                         argument=argument,
                         kwargs=kwargs)

  def _cancel_fn(self, fn):
    """Cancel all events matching the given predicate.

    Args:
      fn: A callable taking an Event and returning True if it should be cancelled.

    Returns:
      The list of cancelled Event instances.
    """
    events = []
    with self._lock:
      pos = []
      for i, qe in enumerate(self._queue):
        if fn(qe):
          events.append(qe)
          pos.append(i)
      if pos:
        # Positions are added in asceending order above, here we pop them in
        # descending order to avoid invalidating positions.
        for i in range(len(pos) - 1, -1, -1):
          self._queue.pop(pos[i])

        heapq.heapify(self._queue)

    return events

  def cancel(self, event):
    """Cancel one or more scheduled events by identity.

    Args:
      event: An Event instance or list/tuple of Event instances.

    Returns:
      The list of cancelled Event instances.
    """
    # Note: Event is a namedtuple - hence a tuple - so a single event must
    # not be treated as a list of events.
    if isinstance(event, (list, tuple)) and not isinstance(event, Event):
      ids = {id(e) for e in event}
      return self._cancel_fn(lambda qe: id(qe) in ids)

    return self._cancel_fn(lambda qe: id(qe) == id(event))

  def ref_cancel(self, ref):
    """Cancel events by their reference identifier.

    Example:
      import py_misc_utils.scheduler as sch

      s = sch.Scheduler()
      s.enter(60.0, lambda: None, ref='cleanup')
      assert s.ref_cancel('cleanup')

    Args:
      ref: A reference string or list/tuple of reference strings.

    Returns:
      The list of cancelled Event instances.
    """
    if isinstance(ref, (list, tuple)):
      refs = set(ref)
      return self._cancel_fn(lambda qe: qe.ref in refs)

    return self._cancel_fn(lambda qe: qe.ref == ref)

  def get_events(self, fn):
    """Return queued events matching a predicate.

    Only events not yet due - still sitting in the queue - are returned:
    once popped, an event is handed to the executor and disappears from
    the scheduler queue even if its action is still running.

    Example:
      import py_misc_utils.scheduler as sch

      s = sch.Scheduler()
      ev = s.enter(60.0, lambda: None)
      assert s.get_events(lambda e: e.ref is None) == [ev]
      s.cancel(ev)

    Args:
      fn: A callable taking an Event and returning True if it matches.

    Returns:
      A list of matching Event instances currently in the queue.
    """
    events = []
    with self._lock:
      for qe in self._queue:
        if fn(qe):
          events.append(qe)

    return events

gen_unique_ref()

Generate a unique reference string for event cancellation.

Returns:

Type Description

A UUID4-based string.

Source code in py_misc_utils/scheduler.py
 94
 95
 96
 97
 98
 99
100
def gen_unique_ref(self):
  """Generate a unique reference string for event cancellation.

  Returns:
    A UUID4-based string.
  """
  return str(uuid.uuid4())

enterabs(ts, action, ref=None, argument=(), kwargs=None)

Schedule an action at an absolute timestamp.

The timestamp is interpreted in the time source of the scheduler (timegen), which by default is the wall clock.

Parameters:

Name Type Description Default
ts

The absolute time to run the action.

required
action

The callable to execute.

required
ref

Optional reference identifier for later cancellation.

None
argument

Positional arguments for action.

()
kwargs

Keyword arguments for action.

None

Returns:

Type Description

The scheduled Event instance.

Source code in py_misc_utils/scheduler.py
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
def enterabs(self, ts, action, ref=None, argument=(), kwargs=None):
  """Schedule an action at an absolute timestamp.

  The timestamp is interpreted in the time source of the scheduler
  (timegen), which by default is the wall clock.

  Args:
    ts: The absolute time to run the action.
    action: The callable to execute.
    ref: Optional reference identifier for later cancellation.
    argument: Positional arguments for action.
    kwargs: Keyword arguments for action.

  Returns:
    The scheduled Event instance.
  """
  with self._lock:
    event = Event(time=ts,
                  sequence=self._sequence,
                  ref=ref,
                  action=action,
                  argument=argument,
                  kwargs=kwargs or {})
    self._sequence += 1

    heapq.heappush(self._queue, event)
    # Notify the scheduler thread only if the new event became the
    # closest-deadline one - otherwise it would just wake up for nothing.
    if id(event) == id(self._queue[0]):
      self._cond.notify()

  return event

enter(delay, action, ref=None, argument=(), kwargs=None)

Schedule an action after a relative delay.

Parameters:

Name Type Description Default
delay

Seconds from now to run the action.

required
action

The callable to execute.

required
ref

Optional reference identifier for later cancellation.

None
argument

Positional arguments for action.

()
kwargs

Keyword arguments for action.

None

Returns:

Type Description

The scheduled Event instance.

Source code in py_misc_utils/scheduler.py
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
def enter(self, delay, action, ref=None, argument=(), kwargs=None):
  """Schedule an action after a relative delay.

  Args:
    delay: Seconds from now to run the action.
    action: The callable to execute.
    ref: Optional reference identifier for later cancellation.
    argument: Positional arguments for action.
    kwargs: Keyword arguments for action.

  Returns:
    The scheduled Event instance.
  """
  return self.enterabs(self.timegen.now() + delay,
                       action,
                       ref=ref,
                       argument=argument,
                       kwargs=kwargs)

cancel(event)

Cancel one or more scheduled events by identity.

Parameters:

Name Type Description Default
event

An Event instance or list/tuple of Event instances.

required

Returns:

Type Description

The list of cancelled Event instances.

Source code in py_misc_utils/scheduler.py
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
def cancel(self, event):
  """Cancel one or more scheduled events by identity.

  Args:
    event: An Event instance or list/tuple of Event instances.

  Returns:
    The list of cancelled Event instances.
  """
  # Note: Event is a namedtuple - hence a tuple - so a single event must
  # not be treated as a list of events.
  if isinstance(event, (list, tuple)) and not isinstance(event, Event):
    ids = {id(e) for e in event}
    return self._cancel_fn(lambda qe: id(qe) in ids)

  return self._cancel_fn(lambda qe: id(qe) == id(event))

ref_cancel(ref)

Cancel events by their reference identifier.

Example
import py_misc_utils.scheduler as sch

s = sch.Scheduler()
s.enter(60.0, lambda: None, ref='cleanup')
assert s.ref_cancel('cleanup')

Parameters:

Name Type Description Default
ref

A reference string or list/tuple of reference strings.

required

Returns:

Type Description

The list of cancelled Event instances.

Source code in py_misc_utils/scheduler.py
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
def ref_cancel(self, ref):
  """Cancel events by their reference identifier.

  Example:
    import py_misc_utils.scheduler as sch

    s = sch.Scheduler()
    s.enter(60.0, lambda: None, ref='cleanup')
    assert s.ref_cancel('cleanup')

  Args:
    ref: A reference string or list/tuple of reference strings.

  Returns:
    The list of cancelled Event instances.
  """
  if isinstance(ref, (list, tuple)):
    refs = set(ref)
    return self._cancel_fn(lambda qe: qe.ref in refs)

  return self._cancel_fn(lambda qe: qe.ref == ref)

get_events(fn)

Return queued events matching a predicate.

Only events not yet due - still sitting in the queue - are returned: once popped, an event is handed to the executor and disappears from the scheduler queue even if its action is still running.

Example
import py_misc_utils.scheduler as sch

s = sch.Scheduler()
ev = s.enter(60.0, lambda: None)
assert s.get_events(lambda e: e.ref is None) == [ev]
s.cancel(ev)

Parameters:

Name Type Description Default
fn

A callable taking an Event and returning True if it matches.

required

Returns:

Type Description

A list of matching Event instances currently in the queue.

Source code in py_misc_utils/scheduler.py
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
def get_events(self, fn):
  """Return queued events matching a predicate.

  Only events not yet due - still sitting in the queue - are returned:
  once popped, an event is handed to the executor and disappears from
  the scheduler queue even if its action is still running.

  Example:
    import py_misc_utils.scheduler as sch

    s = sch.Scheduler()
    ev = s.enter(60.0, lambda: None)
    assert s.get_events(lambda e: e.ref is None) == [ev]
    s.cancel(ev)

  Args:
    fn: A callable taking an Event and returning True if it matches.

  Returns:
    A list of matching Event instances currently in the queue.
  """
  events = []
  with self._lock:
    for qe in self._queue:
      if fn(qe):
        events.append(qe)

  return events

common_scheduler()

Return the process-wide common Scheduler instance, creating it if needed.

Returns:

Type Description

The shared Scheduler backed by the common executor.

Source code in py_misc_utils/scheduler.py
253
254
255
256
257
258
259
260
261
262
263
264
265
def common_scheduler():
  """Return the process-wide common Scheduler instance, creating it if needed.

  Returns:
    The shared Scheduler backed by the common executor.
  """
  global _SCHEDULER

  with _LOCK:
    if _SCHEDULER is None:
      _SCHEDULER = Scheduler(executor=xe.common_executor())

    return _SCHEDULER