Table Of Contents
Clock object¶
The Clock
object allows you to schedule a function call in the
future; once or repeatedly at specified intervals. You can get the time
elapsed between the scheduling and the calling of the callback via the
dt argument:
# dt means delta-time
def my_callback(dt):
pass
# call my_callback every 0.5 seconds
Clock.schedule_interval(my_callback, 0.5)
# call my_callback in 5 seconds
Clock.schedule_once(my_callback, 5)
# call my_callback as soon as possible (usually next frame.)
Clock.schedule_once(my_callback)
Note
If the callback returns False, the schedule will be removed.
If you want to schedule a function to call with default arguments, you can use the functools.partial python module:
from functools import partial
def my_callback(value, key, *largs):
pass
Clock.schedule_interval(partial(my_callback, 'my value', 'my key'), 0.5)
Conversely, if you want to schedule a function that doesn’t accept the dt argument, you can use a lambda expression to write a short function that does accept dt. For Example:
def no_args_func():
print("I accept no arguments, so don't schedule me in the clock")
Clock.schedule_once(lambda dt: no_args_func(), 0.5)
Note
You cannot unschedule an anonymous function unless you keep a reference to it. It’s better to add *args to your function definition so that it can be called with an arbitrary number of parameters.
Important
The callback is weak-referenced: you are responsible for keeping a reference to your original object/callback. If you don’t keep a reference, the ClockBase will never execute your callback. For example:
class Foo(object):
def start(self):
Clock.schedule_interval(self.callback, 0.5)
def callback(self, dt):
print('In callback')
# A Foo object is created and the method start is called.
# Because no reference is kept to the instance returned from Foo(),
# the object will be collected by the Python Garbage Collector and
# your callback will be never called.
Foo().start()
# So you should do the following and keep a reference to the instance
# of foo until you don't need it anymore!
foo = Foo()
foo.start()
Schedule before frame¶
New in version 1.0.5.
Sometimes you need to schedule a callback BEFORE the next frame. Starting from 1.0.5, you can use a timeout of -1:
Clock.schedule_once(my_callback, 0) # call after the next frame
Clock.schedule_once(my_callback, -1) # call before the next frame
The Clock will execute all the callbacks with a timeout of -1 before the
next frame even if you add a new callback with -1 from a running
callback. However, Clock
has an iteration limit for these
callbacks: it defaults to 10.
If you schedule a callback that schedules a callback that schedules a .. etc more than 10 times, it will leave the loop and send a warning to the console, then continue after the next frame. This is implemented to prevent bugs from hanging or crashing the application.
If you need to increase the limit, set the max_iteration
property:
from kivy.clock import Clock
Clock.max_iteration = 20
Triggered Events¶
New in version 1.0.5.
A triggered event is a way to defer a callback exactly like schedule_once(),
but with some added convenience. The callback will only be scheduled once per
frame even if you call the trigger twice (or more). This is not the case
with Clock.schedule_once()
:
# will run the callback twice before the next frame
Clock.schedule_once(my_callback)
Clock.schedule_once(my_callback)
# will run the callback once before the next frame
t = Clock.create_trigger(my_callback)
t()
t()
Before triggered events, you may have used this approach in a widget:
def trigger_callback(self, *largs):
Clock.unschedule(self.callback)
Clock.schedule_once(self.callback)
As soon as you call trigger_callback(), it will correctly schedule the
callback once in the next frame. It is more convenient to create and bind to
the triggered event than using Clock.schedule_once()
in a function:
from kivy.clock import Clock
from kivy.uix.widget import Widget
class Sample(Widget):
def __init__(self, **kwargs):
self._trigger = Clock.create_trigger(self.cb)
super(Sample, self).__init__(**kwargs)
self.bind(x=self._trigger, y=self._trigger)
def cb(self, *largs):
pass
Even if x and y changes within one frame, the callback is only run once.
Note
ClockBase.create_trigger()
also has a timeout parameter that
behaves exactly like ClockBase.schedule_once()
.
Threading¶
New in version 1.9.0.
Often, other threads are used to schedule callbacks with kivy’s main thread
using ClockBase
. Therefore, it’s important to know what is thread safe
and what isn’t.
All the ClockBase
and ClockEvent
methods are safe with
respect to kivy’s thread. That is, it’s always safe to call these methods
from a single thread that is not the kivy thread. However, there are no
guarantees as to the order in which these callbacks will be executed.
Calling a previously created trigger from two different threads (even if one
of them is the kivy thread), or calling the trigger and its
ClockEvent.cancel()
method from two different threads at the same time is
not safe. That is, although no exception will be raised, there no guarantees
that calling the trigger from two different threads will not result in the
callback being executed twice, or not executed at all. Similarly, such issues
might arise when calling the trigger and canceling it with
ClockBase.unschedule()
or ClockEvent.cancel()
from two threads
simultaneously.
Therefore, it is safe to call ClockBase.create_trigger()
,
ClockBase.schedule_once()
, ClockBase.schedule_interval()
, or
call or cancel a previously created trigger from an external thread.
The following code, though, is not safe because it calls or cancels
from two threads simultaneously without any locking mechanism:
event = Clock.create_trigger(func)
# in thread 1
event()
# in thread 2
event()
# now, the event may be scheduled twice or once
# the following is also unsafe
# in thread 1
event()
# in thread 2
event.cancel()
# now, the event may or may not be scheduled and a subsequent call
# may schedule it twice
Note, in the code above, thread 1 or thread 2 could be the kivy thread, not just an external thread.
-
class
kivy.clock.
ClockBase
[source]¶ Bases:
kivy.clock._ClockBase
A clock object with event support.
-
create_trigger
(callback, timeout=0)[source]¶ Create a Trigger event. Check module documentation for more information.
Returns: A ClockEvent
instance. To schedule the callback of this instance, you can call it.New in version 1.0.5.
-
frames
¶ Number of internal frames (not necesseraly drawed) from the start of the clock.
New in version 1.8.0.
-
frames_displayed
¶ Number of displayed frames from the start of the clock.
-
frametime
¶ Time spent between the last frame and the current frame (in seconds).
New in version 1.8.0.
-
get_rfps
()[source]¶ Get the current “real” FPS calculated by the clock. This counter reflects the real framerate displayed on the screen.
In contrast to get_fps(), this function returns a counter of the number of frames, not the average of frames per second.
-
max_iteration
¶ New in version 1.0.5: When a schedule_once is used with -1, you can add a limit on how iteration will be allowed. That is here to prevent too much relayout.
-
schedule_interval
(callback, timeout)[source]¶ Schedule an event to be called every <timeout> seconds.
Returns: A ClockEvent
instance. As opposed tocreate_trigger()
which only creates the trigger event, this method also schedules it.
-
schedule_once
(callback, timeout=0)[source]¶ Schedule an event in <timeout> seconds. If <timeout> is unspecified or 0, the callback will be called after the next frame is rendered.
Returns: A ClockEvent
instance. As opposed tocreate_trigger()
which only creates the trigger event, this method also schedules it.Changed in version 1.0.5: If the timeout is -1, the callback will be called before the next frame (at
tick_draw()
).
-
tick
()[source]¶ Advance the clock to the next step. Must be called every frame. The default clock has a tick() function called by the core Kivy framework.
-
time
= <functools.partial object>¶
-
unschedule
(callback, all=True)[source]¶ Remove a previously scheduled event.
Parameters: - callback:
ClockEvent
or a callable. If it’s a
ClockEvent
instance, then the callback associated with this event will be canceled if it is scheduled. If it’s a callable, then the callable will be unscheduled if it is scheduled.- all: bool
If True and if callback is a callable, all instances of this callable will be unscheduled (i.e. if this callable was scheduled multiple times). Defaults to True.
Changed in version 1.9.0: The all parameter was added. Before, it behaved as if all was True.
- callback:
-
-
class
kivy.clock.
ClockEvent
(clock, loop, callback, timeout, starttime, cid, trigger=False)[source]¶ Bases:
object
A class that describes a callback scheduled with kivy’s
Clock
. This class is never created by the user; instead, kivy creates and returns an instance of this class when scheduling a callback.Warning
Most of the methods of this class are internal and can change without notice. The only exception are the
cancel()
and__call__()
methods.
-
kivy.clock.
mainthread
(func)[source]¶ Decorator that will schedule the call of the function for the next available frame in the mainthread. It can be useful when you use
UrlRequest
or when you do Thread programming: you cannot do any OpenGL-related work in a thread.Please note that this method will return directly and no result can be returned:
@mainthread def callback(self, *args): print('The request succedded!', 'This callback is called in the main thread.') self.req = UrlRequest(url='http://...', on_success=callback)
New in version 1.8.0.