# Calling functions periodically

pyglet applications begin execution with:

    pyglet.app.run()

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:

- A user input event (such as a mouse movement or key press) has been generated. In this case the appropriate code can be attached as an event handler to the window.
- An animation or other time-dependent system needs to update the position or parameters of an object. We'll call this a "periodic" event.
- A certain amount of time has passed, perhaps indicating that an operation has timed out, or that a dialog can be automatically dismissed. We'll call this a "one-shot" event.

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):
        # ...
    pyglet.clock.schedule(update)

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.