Skip to content

Core API

Batteries-included

Reach for these first: SupervisedService composes a service and its supervisor, starts the loop in a background thread, and offers stop(), is_running, and a context manager.

bgt.SupervisedService

Handle for a service that runs under supervision.

Construct via start().

is_running property

Return whether the supervising thread is still alive.

__enter__()

Return the running service itself.

__exit__(exc_type, exc, tb)

Stop on exit, whether or not the body raised.

start(work_factory, *, name, wakeup, interval=1.0, initial_backoff=0.1) classmethod

Build a service for work_factory and start running it under a Supervisor.

name names the service, the supervisor, its thread, and the restart metric’s label.

See Service.build() for the service arguments and Supervisor.start() for initial_backoff.

stop(timeout=None)

Stop the supervision and the service loop.

See Supervisor.stop().

bgt.IntervalOnlyWakeup

The wakeup for a service that has no external wake source.

It starts woken, so a service’s first work unit runs at startup.

After that, wait() only ever times out and the Service polls on its own interval. wake() ends the wait instantly.

Other wakeups exist: pgbg’s Subscription wakes a service on PostgreSQL NOTIFYs, over a single database connection per process.

close()

Release nothing: there is no external source behind this wakeup.

wait(timeout)

Block up to timeout seconds.

Parameters:

Name Type Description Default
timeout float

Maximum time to wait for a wakeup.

required

Return True when woken and False on a timeout.

wake()

End the current wait and let the loop re-check its stop event.

bgt.as_work_factory(do_work)

Wrap a plain do_work callable into a WorkFactory with no setup or cleanup.

Parameters:

Name Type Description Default
do_work DoWork

A callable that performs one bounded work unit.

required

Returns:

Type Description
WorkFactory

A factory that creates a context manager returning do_work.

See also

as_async_work_factory() for asynchronous callables.

bgt.as_async_work_factory(do_async_work, *, debug=None, loop_factory=None)

Wrap an async do_async_work callable into a WorkFactory with no setup or cleanup.

Note

This is a lightweight helper for simple but common use cases.

As such:

  • The work factory creates and owns the asyncio.Runner and its event loop.

  • The event loop only runs during a work unit. Background tasks and timers do not run between work units.

If you need more control over the event loop’s or the runner’s lifecycle, create your own WorkFactory implementation. It’s only a handful of lines of code.

Parameters:

Name Type Description Default
do_async_work DoAsyncWork

An async callable that performs one bounded work unit.

required
debug bool | None

When true, the event loop will be run in debug mode. None means asyncio’s default.

None
loop_factory Callable[[], AbstractEventLoop] | None

When passed, it is used for new event loop creation.

None

Returns:

Type Description
WorkFactory

A factory that creates a context manager returning a plain callable that runs one async work unit.

See also

as_work_factory() for synchronous callables.

Escape hatches

You do not have to use bgt’s supervision: Service is a plain blocking loop that you can run on a thread you own, for example your main thread, under a process supervisor.

You can also implement a Loop of your own.

bgt.Service

Loop for a background service.

Runs work units and waits on a Wakeup between loop cycles.

Users must create it using build().

build(work_factory, *, name, wakeup, interval=1.0) classmethod

Validate arguments and build a service, ready to be supervised.

Hand the result to Supervisor.start(), to run it supervised in a background thread.

Parameters:

Name Type Description Default
work_factory WorkFactory required
name str

Names the service in logs and metrics. Must not be empty.

required
wakeup Wakeup

Ends the wait between loop cycles. See Wakeup. An IntervalOnlyWakeup polls on interval alone. pgbg’s Subscription adds notification-driven wakeups.

Warning

Do not share this wakeup with another consumer. The service takes exclusive ownership and closes it when supervision ends.

required
interval float

Maximum seconds to wait for a wakeup. The service runs again (performs a loop cycle) when this interval expires. Must be greater than zero.

1.0

Raises:

Type Description
ValueError

If interval or name are invalid.

close()

Release the wakeup.

run(stop)

Wait for wakeups and work until stop is set.

Enters the work factory first: it creates the loop run’s do_work, and its cleanup runs when the loop run ends, crash or not.

Any failure propagates and a clean return means stop was set. A factory that suppresses the loop run’s crash raises SuppressedCrashError instead.

Parameters:

Name Type Description Default
stop Event

The event the loop exits on.

required

wake()

Wake the loop out of its wait so a set stop takes effect promptly.

bgt.Supervisor

Runs a loop in a background thread and restarts it when it dies.

Owns the loop’s thread, its stop event, and the restart policy. Crashes are instrumented and retried after an exponential backoff. A persistently broken loop crash-loops with backoff and heals as soon as its cause is fixed.

Users must create instances with start().

Can be used as a context manager that automatically stops the loop on exit.

is_running property

Return whether the supervisor thread is still alive.

start(loop, *, name, initial_backoff=0.1) classmethod

Build and start the supervisor thread.

Parameters:

Name Type Description Default
loop Loop

The loop this supervisor keeps alive.

required
name str

Identifies this supervisor in its thread name, logs, and the restart metric’s label.

required
initial_backoff float

How long the supervisor waits after a crash before restarting.

0.1

stop(timeout=None)

Signal everything to stop and wait for the thread to exit.

Idempotent.

Parameters:

Name Type Description Default
timeout float | None

Maximum time to wait for the thread to exit. None means wait indefinitely.

None

Returns:

Type Description
bool

True if the thread exited within the timeout, False otherwise.

Exceptions

bgt.exceptions.SuppressedCrashError

Bases: RuntimeError

A work factory’s context manager swallowed the exception that ended a loop run.

This looks like a clean, silent stop to the supervisor which is almost certainly undesired.