timers — a simple timer

Timer reference

class timers.Timer(callback_func)

Timer will call the callback_func callable after time specified when calling the start() or start_global() method.

The callback_func callable implementation receives one parameter - timer_context which is a TimerContext instance.

def my_func(self, timer_context):
    print('Triggered by the timer!')

global_timer = Timer(my_func)
global_timer.start_global(1.5)  # in seconds
# ... somewhere inside a Scene:

def my_func(self, timer_context):
    print('Triggered by the timer!')

def add_timer(self):
    timer = Timer(my_func)
    timer.start(1.5, scene=self)  # in seconds

The callback_func may return a numeric value. It will reset the timer, allowing to run it in a loop:

def my_func(self, timer_context):
    new_interval = random.uniform(1.0, 2.0)
    print('Resetting the timer with interval of {} seconds'.format(new_interval))
    return new_interval  # this resets the timer

global_timer = Timer(my_func)
global_timer.start_global(1.5)  # in seconds

Instance properties:

Timer.is_running

Returns True if the timer is running.

Instance methods:

Timer.start(interval, scene)

Starts the timer in a context of a specific engine.Scene instance. After interval seconds, the timer’s callback function (defined in the constructor) will be invoked.

There are few reasons why you may want a scene instance associated with a timer:

  • If you change scene to a new one, the timers associated with the previous scene will stop running automatically

  • When a scene gets destroyed, timers associated with that scene will be destroyed as well and you won’t receive any surprise callbacks.

  • Timers utilize engine.Scene.time_scale property.

Calling start() on a running timer resets the timer.

Timer.start_global(interval)

Same as start() but does not require passing a scene. Use it if you need a “global” timer.

Timer.stop()

Stops the timer.

TimerContext reference

An object passed to timer’s callback function

Instance properties:

TimerContext.scene

Read only. Gets the scene (as engine.Scene instance). Will be None if timer was called with Timer.start_global() method.

TimerContext.interval

Read only. Interval with which the timer was called.