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