Calling functions periodically

pyglet applications begin execution with:

Once called, this function doesn't return until the application windows have been closed. This may leave you wondering how to execute code while the application is running.

Typical applications need to execute code in only three circumstances:

To have a function called periodically, for example, once every 0.1 seconds:

def update(dt):
    # ...
pyglet.clock.schedule_interval(update, 0.1)

The dt parameter gives the number of seconds (due to latency, load and timer inprecision, this might be slightly more or less than the requested interval).

Scheduling functions with a set interval is ideal for animation, physics simulation, and game state updates. pyglet ensures that the application does not consume more resources than necessary to execute the scheduled functions in time.

Rather than "limiting the frame rate", as required in other toolkits, simply schedule all your update functions for no less than the minimum period your application or game requires. For example, most games need not run at more than 60Hz (60 times a second) for imperceptibly smooth animation, so the interval given to schedule_interval would be 1/60.0 (or more).

If you are writing a benchmarking program or otherwise wish to simply run at the highest possible frequency, use schedule:

def update(dt):
    # ...

By default pyglet window buffer swaps are synchronised to the display refresh rate, so you may also want to disable set_vsync.

For one-shot events, use schedule_once:

def dismiss_dialog(dt):
    # ...

# Dismiss the dialog after 5 seconds.
pyglet.clock.schedule_once(dismiss_dialog, 5.0)

To stop a scheduled function from being called, including cancelling a periodic function, use pyglet.clock.unschedule.