pyglet.clock

Precise framerate calculation function scheduling.

The clock module allows you to schedule functions to run periodically, or for one-shot future execution. pyglet’s default event loop (run()) keeps an internal instance of a Clock, which is ticked automatically.

Note

Some internal modules will schedule items on the clock. If you are using a custom event loop, always remember to tick the clock!

Scheduling

You can schedule a function to be called every time the clock is ticked:

def callback(dt):
    print(f"{dt} seconds since last callback")

clock.schedule(callback)

The schedule_interval method causes a function to be called every “n” seconds:

clock.schedule_interval(callback, 0.5)   # called twice a second

The schedule_once method causes a function to be called once “n” seconds in the future:

clock.schedule_once(callback, 5)        # called in 5 seconds

All the schedule methods will pass on any additional args or keyword args you specify to the callback function:

def move(dt, velocity, sprite):
    sprite.position += dt * velocity

clock.schedule(move, velocity=5.0, sprite=alien)

You can cancel a function scheduled with any of these methods using unschedule:

clock.unschedule(move)

Using multiple clocks

The clock functions are all relayed to an instance of Clock which is initialised with the module. You can get this instance to use directly:

clk = pyglet.clock.get_default()

You can also replace the default clock with your own:

myclk = pyglet.clock.Clock() pyglet.clock.set_default(myclk)

Each clock maintains its own set of scheduled functions and frequency measurement. Each clock must be “ticked” separately.

Multiple and derived clocks potentially allow you to separate “game-time” and “wall-time”, or to synchronise your clock to an audio or video stream instead of the system clock.

exception ChainStopped

Raised in a waiting chain when one of its child chains stops.

class Chain(
generator: Generator[float | int | Chain | YieldingOperation | None, Any, Any],
clock: Clock | None = None,
) → None

Run generator-based sequences on a pyglet clock.

Chains yield delays, child chains, callback operations, or None. They can be stopped as a group and exposes callbacks.

Initialize the chain with a generator.

add_callbacks(
**callbacks: Callable[[...], Any],
) → Chain

Register strongly referenced callbacks and return this chain.

Accepted names are on_complete, on_stop, on_pause, on_resume, and on_error.

Return type:

Chain

pause() → Chain

Pauses the chain, with the intention to either resume or stop in the future.

Cannot resume if chain was stopped.

Return type:

Chain

resume() → Chain

Resumes the chain if it was paused.

Cannot resume if chain was stopped.

Return type:

Chain

start() → Chain
Return type:

Chain

stop() → None

Stops the chain from running.

Return type:

None

property clock: Clock
property completed: bool
property done: bool
exception: BaseException | None
property failed: bool
on_complete: Callable[[Any], Any] | None
on_error: Callable[[BaseException], Any] | None
on_pause: Callable[[], Any] | None
on_resume: Callable[[], Any] | None
on_stop: Callable[[], Any] | None
property paused: bool
result: Any
property running: bool
property stopped: bool
class ChainGroup(clock: Clock | None = None) → None

Track related chains and child groups for lifecycle control.

Initialize the group with an optional clock for unbound chains.

add(
chain: Chain,
*,
tag: str | None = None,
tags: Iterable[str] = (),
) → Chain

Track a chain without starting it.

Return type:

Chain

add_group(group: ChainGroup) → ChainGroup

Add an existing child group and return it.

Return type:

ChainGroup

clear(
*,
tag: str | None = None,
tags: Iterable[str] = (),
) → ChainGroup

Stop and forget tracked chains, optionally filtered by tag.

Return type:

ChainGroup

create_group(
clock: Clock | None = None,
) → ChainGroup

Create, add, and return a child group.

Return type:

ChainGroup

pause(
*,
tag: str | None = None,
tags: Iterable[str] = (),
) → ChainGroup

Pause tracked chains and child groups, optionally filtered by tag.

Return type:

ChainGroup

resume(
*,
tag: str | None = None,
tags: Iterable[str] = (),
) → ChainGroup

Resume tracked chains and child groups, optionally filtered by tag.

Return type:

ChainGroup

start(
chain: Chain,
*,
tag: str | None = None,
tags: Iterable[str] = (),
) → Chain

Track and start a chain, or return it unchanged if already done.

Return type:

Chain

stop(
*,
tag: str | None = None,
tags: Iterable[str] = (),
) → ChainGroup

Alias for clear().

Return type:

ChainGroup

property chains: tuple[Chain, ...]
property clock: Clock
property groups: tuple[ChainGroup, ...]
property paused: bool
class Clock(time_function: Callable = <built-in function perf_counter>) → None

Schedule callbacks and chains against a single time source.

Each clock maintains its own scheduled callbacks, chain state, and frequency measurements. Custom clocks can be ticked independently to separate gameplay time, UI time, or other application timelines.

Initialize a Clock, with optional custom time function.

You can provide a custom time function to return the elapsed time of the application, in seconds. Defaults to time.perf_counter, but can be replaced to allow for easy time dilation effects or game pausing.

static sleep(microseconds: float) → None
Return type:

None

call_scheduled_functions(dt: float) → bool

Call scheduled functions that elapsed on the last update_time.

This method is called automatically when the clock is ticked (see tick()), so you need not call it yourself in most cases.

Parameters:

dt (float) – The elapsed time since the last update to pass to each scheduled function. This is not used to calculate which functions have elapsed.

Return type:

bool

Returns: True if any functions were called, else False.

chain(
function: Callable[[...], Generator[float | int | Chain | YieldingOperation | None, Any, T]],
) → Callable[[...], Chain]

Decorate a generator function so returned chains use this clock.

Return type:

Callable[..., Chain]

create_group() → ChainGroup

Create a chain group bound to this clock.

Return type:

ChainGroup

get_frequency() → float

Get the average clock update frequency of recent history.

The result is the average of a sliding window of the last “n” updates, where “n” is some number designed to cover approximately 1 second. This is the clock frequency, not the Window redraw rate (fps).

Return type:

float

get_sleep_time(sleep_idle: bool) → float | None

Get the time until the next item is scheduled, if any.

Applications can choose to continue receiving updates at the maximum framerate during idle time (when no functions are scheduled), or they can sleep through their idle time and allow the CPU to switch to other processes or run in low-power mode.

If sleep_idle is True the latter behaviour is selected, and None will be returned if there are no scheduled items.

Otherwise, if sleep_idle is False, or if any scheduled items exist, a value of 0 is returned.

Parameters:

sleep_idle (bool) – If True, the application intends to sleep through its idle time; otherwise it will continue ticking at the maximum frame rate allowed.

Return type:

float | None

parallel(
*chains: Chain,
continue_on_stop: bool = False,
) → _ParallelOperation

Run child chains on this clock and resume with their ordered results.

Return type:

_ParallelOperation

race(*chains: Chain) → _RaceOperation

Run child chains on this clock and resume with the first result.

Return type:

_RaceOperation

repeat(
factory: Callable[[], Chain],
count: int,
) → Chain

Create a repeat chain on this clock.

Return type:

Chain

repeat_duration(
factory: Callable[[], Chain],
duration: float,
) → Chain

Create a duration-limited repeat chain on this clock.

Return type:

Chain

repeat_forever(
factory: Callable[[], Chain],
) → Chain

Create an indefinite repeat chain on this clock.

Return type:

Chain

repeat_until(
factory: Callable[[], Chain],
condition: Callable[[], bool],
) → Chain

Create a repeat-until chain on this clock.

Return type:

Chain

schedule(
func: Callable,
*args: Any,
**kwargs: Any,
) → None

Schedule a function to be called every tick.

The scheduled function should have a prototype that includes dt as the first argument, which gives the elapsed time in seconds since the last clock tick. Any additional args or kwargs given to this method are passed on to the callback:

def callback(dt, *args, **kwargs):
    pass
Return type:

None

Note

Functions scheduled using this method will be called every tick by the default pyglet event loop, which can lead to high CPU usage. It is usually better to use schedule_interval() unless this is desired.

schedule_interval(
func: Callable,
interval: float,
*args: Any,
**kwargs: Any,
) → None

Schedule a function to be called every interval seconds.

To schedule a function to be called at 60Hz (60fps), you would use 1/60 for the interval, and so on. The clock follows the requested series of times. If a callback is late but its following time has not passed, that following time is kept. A late callback can therefore be followed by a shorter gap.

If pyglet misses one or more complete calls, those calls are skipped rather than replayed. The next times of callbacks that are overdue together are spread apart to avoid a burst of catch-up work. Delays can occur when the main thread is overloaded or blocked.

The callback function prototype is the same as for schedule().

Note

Specifying an interval of 0 will prevent the function from being called again. If you want to schedule a function to be called as often as possible, see schedule().

Return type:

None

schedule_interval_fixed_delay(
func: Callable,
interval: float,
*args: Any,
**kwargs: Any,
) → None

Schedule a function with a fixed delay after each completed call.

Unlike schedule_interval(), the next deadline is calculated from the time the callback finishes. This prevents a long-running callback from immediately becoming due again. Callbacks initially due together can acquire different next times according to when each one finishes.

The time from the start of one call to the next is approximately the callback’s runtime plus interval. Missed calls are never accumulated, and callback runtime does not expand the set of callbacks eligible in the current clock tick.

This is useful for polling and maintenance work where the delay between completed operations matters more than maintaining the original series of requested times.

Note

Specifying an interval of 0 will prevent the function from being called again.

Note

This is not a fixed time step implementation.

Return type:

None

schedule_interval_for_duration(
func: Callable,
interval: float,
duration: float,
*args: Any,
**kwargs: Any,
) → None

Temporarily schedule a function to be called every interval seconds.

This method will schedule a function to be called every interval seconds (see schedule_interval()), but will automatically unschedule it after duration seconds.

The callback function prototype is the same as for schedule().

Args:
func:

The function to call when the timer lapses.

interval:

The number of seconds to wait between each call.

duration:

The number of seconds for which the function is scheduled.

Return type:

None

schedule_interval_soft(
func: Callable,
interval: float,
*args: Any,
**kwargs: Any,
) → None

Schedule a function to be called approximately every interval seconds.

This method is similar to schedule_interval(), except that the clock chooses a different starting time from nearby scheduled functions in order to distribute CPU load more evenly.

This is useful for functions that need to be called regularly, but not relative to the initial start time. pyglet.media does this for scheduling audio buffer updates, which need to occur regularly – if all audio updates are scheduled at the same time (for example, mixing several tracks of a music score, or playing multiple videos back simultaneously), the resulting load on the CPU is excessive for those intervals but idle outside. Using the soft interval scheduling, the load is more evenly distributed.

Soft interval scheduling can also start repeating animations at different points in their cycles; for example, multiple flags waving in the wind.

Return type:

None

schedule_once(
func: Callable,
delay: float,
*args: Any,
**kwargs: Any,
) → None

Schedule a function to be called once after delay seconds.

The callback function prototype is the same as for schedule().

Return type:

None

tick(poll: bool = False) → float

Signify that one frame has passed.

This will call any scheduled functions that have elapsed, and returns the number of seconds since the last time this method has been called. The first time this method is called, 0 is returned.

Parameters:

poll (bool) – If True, the function will call any scheduled functions but will not sleep or busy-wait for any reason. Recommended for advanced applications managing their own sleep timers only.

Return type:

float

timeout(delay: float) → Chain

Create a chain on this clock that completes after delay seconds.

Return type:

Chain

tween(duration: float, update: ~typing.Callable[[float], ~typing.Any], *, easing: ~typing.Callable[[float], float] = <function linear>) → Chain

Create a tween chain driven by this clock.

Return type:

Chain

unschedule(func: Callable) → None

Remove a function from the schedule.

If the function appears in the schedule more than once, all occurrences are removed. If the function was not scheduled, no error is raised.

Return type:

None

update_time() → float

Get the elapsed time since the last call to update_time.

This updates the clock’s internal measure of time and returns the difference (in seconds) since the last time it was called. The first call of this method always returns 0.

Return type:

float

times: deque
class YieldInstruction(
starter: Callable[[Callable[[Any], None], Callable[[BaseException], None]], Callable[[], None] | None],
) → None

Adapt a callback-driven API into a yield instruction.

Initialize the operation with a callback starter.

start(
complete: Callable[[Any], None],
fail: Callable[[BaseException], None],
) → Callable[[], None] | None
Return type:

Callable[[], None] | None

class YieldingOperation(*args, **kwargs)

A yield instruction that can wake a suspended chain.

start(
complete: Callable[[Any], None],
fail: Callable[[BaseException], None],
) → Callable[[], None] | None
Return type:

Callable[[], None] | None

chain(
function: Callable[[...], Generator[float | int | Chain | YieldingOperation | None, Any, T]],
*,
clock: Clock | None = None,
) → Callable[[...], Chain]

Decorate a generator function so it returns a Chain.

Return type:

Callable[..., Chain]

ease_in(progress: float) → float

Accelerate from rest using quadratic easing.

Return type:

float

ease_in_out(progress: float) → float

Accelerate and then decelerate using quadratic easing.

Return type:

float

ease_out(progress: float) → float

Decelerate to rest using quadratic easing.

Return type:

float

from_callback(
starter: Callable[[Callable[[Any], None], Callable[[BaseException], None]], Callable[[], None] | None],
) → YieldInstruction

Create a yield instruction from a callback-based function.

Return type:

YieldInstruction

get_default() → Clock

Get the pyglet default Clock.

Return the Clock instance that is used by all module-level clock functions.

Return type:

Clock

get_frequency() → float
See:

get_frequency().

Return type:

float

get_sleep_time(sleep_idle: bool) → float | None
See:

get_sleep_time().

Return type:

float | None

linear(progress: float) → float

Return unchanged progress for constant-speed interpolation.

Return type:

float

parallel(
*chains: Chain,
continue_on_stop: bool = False,
) → _ParallelOperation

Run child chains concurrently and resume with their ordered results.

Return type:

_ParallelOperation

race(*chains: Chain) → _RaceOperation

Run child chains concurrently and resume with the first result.

Return type:

_RaceOperation

repeat(
factory: Callable[[], Chain],
count: int,
*,
clock: Clock | None = None,
) → Chain

Create a chain that runs a child-chain factory count times.

Return type:

Chain

repeat_duration(
factory: Callable[[], Chain],
duration: float,
*,
clock: Clock | None = None,
) → Chain

Create a chain that repeats child chains until duration elapses.

Return type:

Chain

repeat_forever(
factory: Callable[[], Chain],
*,
clock: Clock | None = None,
) → Chain

Create a chain that repeats child chains until stopped.

Return type:

Chain

repeat_until(
factory: Callable[[], Chain],
condition: Callable[[], bool],
*,
clock: Clock | None = None,
) → Chain

Create a chain that repeats child chains until condition is true.

Return type:

Chain

schedule(func: Callable, *args: Any, **kwargs: Any) → None
See:

schedule().

Return type:

None

schedule_interval(
func: Callable,
interval: float,
*args: Any,
**kwargs: Any,
) → None
See:

schedule_interval().

Return type:

None

schedule_interval_fixed_delay(
func: Callable,
interval: float,
*args: Any,
**kwargs: Any,
) → None
See:

schedule_interval_fixed_delay().

Return type:

None

schedule_interval_for_duration(
func: Callable,
interval: float,
duration: float,
*args,
**kwargs,
) → None
See:

schedule_interval_for_duration().

Return type:

None

schedule_interval_soft(
func: Callable,
interval: float,
*args,
**kwargs,
) → None
See:

schedule_interval_soft().

Return type:

None

schedule_once(func: Callable, delay: float, *args, **kwargs) → None
See:

schedule_once().

Return type:

None

set_default(default: Clock) → None

Set the default clock to use for all module-level functions.

By default, an instance of Clock is used.

Return type:

None

smoothstep(progress: float) → float

Interpolate with zero first derivatives at both endpoints.

Return type:

float

tick(poll: bool = False) → float
See:

tick().

Return type:

float

timeout(
delay: float,
*,
clock: Clock | None = None,
) → Chain

Create a chain that completes after delay seconds.

Return type:

Chain

tween(duration: float, update: ~typing.Callable[[float], ~typing.Any], *, easing: ~typing.Callable[[float], float] = <function linear>, clock: ~pyglet.clock.Clock | None = None) → Chain

Create a tween chain that updates eased progress over a duration.

Return type:

Chain

unschedule(func: Callable) → None
See:

unschedule().

Return type:

None

wait_for_event(
dispatcher: EventDispatcher,
event_type: str,
*,
condition: Callable[[...], bool] | None = None,
consume: bool = False,
) → YieldInstruction

Create a yield instruction that completes on a dispatcher event.

The temporary handler is removed when the event matches or when the waiting chain is stopped.

Return type:

YieldInstruction

yielding_callback(
function: Callable[[...], Callable[[], None] | None],
) → Callable[[...], YieldInstruction]

Decorate a callback starter so it can be yielded from a chain.

Return type:

Callable[..., YieldInstruction]

STOPPED = STOPPED

Used when something continues after a stop.