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.

class Clock(time_function=<built-in function perf_counter>)
call_scheduled_functions(dt: float) bool

Call scheduled functions that elapsed on the last update_time.

Returns True if any functions were called, otherwise False.

New in version 1.2.

Parameters
dtfloat

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

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 not the Window redraw rate.

get_sleep_time(sleep_idle: bool)

Get the time until the next item is scheduled.

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_idlebool

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

Returns

Time until the next scheduled event in seconds, or None if there is no event scheduled.

New in version 1.1.

schedule(func, *args, **kwargs)

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
Parameters
funccallable

The function to call each tick.

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, interval, *args, **kwargs)

Schedule a function to be called every interval seconds.

Specifying an interval of 0 prevents the function from being called again (see schedule to call a function as often as possible).

The callback function prototype is the same as for schedule.

Parameters
funccallable

The function to call when the timer lapses.

intervalfloat

The number of seconds to wait between each call.

schedule_interval_for_duration(func, interval, duration, *args, **kwargs)

Schedule a function to be called every interval seconds (see schedule_interval) and unschedule it after duration seconds.

The callback function prototype is the same as for schedule.

Parameters
funccallable

The function to call when the timer lapses.

intervalfloat

The number of seconds to wait between each call.

durationfloat

The number of seconds for which the function is scheduled.

schedule_interval_soft(func, interval, *args, **kwargs)

Schedule a function to be called every interval seconds.

This method is similar to schedule_interval, except that the clock will move the interval out of phase with other 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 be used as an easy way to schedule graphics animations out of phase; for example, multiple flags waving in the wind.

New in version 1.1.

Parameters
funccallable

The function to call when the timer lapses.

intervalfloat

The number of seconds to wait between each call.

schedule_once(func, delay, *args, **kwargs)

Schedule a function to be called once after delay seconds.

The callback function prototype is the same as for schedule.

Parameters
funccallable

The function to call when the timer lapses.

delayfloat

The number of seconds to wait before the timer lapses.

static sleep(microseconds: float)
tick(poll=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
pollbool

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.

unschedule(func)

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.

Parameters
funccallable

The function to remove from the schedule.

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.

get_default()

Get the pyglet default Clock.

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

get_frequency() float
See

get_frequency()

get_sleep_time(sleep_idle: bool) float
See

get_sleep_time()

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

schedule()

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

schedule_interval()

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

schedule_interval_for_duration()

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

schedule_interval_soft()

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

schedule_once()

set_default(default) None

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

By default, an instance of Clock is used.

tick(poll: bool = False) float
See

tick()

unschedule(func: Callable) None
See

unschedule()