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 canceled and won’t repeat.
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 class method 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.
CyClockBase.create_trigger()
is an advanced method way to defer a
callback. It functions exactly like CyClockBase.schedule_once()
and
CyClockBase.schedule_interval()
except that it doesn’t immediately
schedule the callback. Instead, one schedules the callback using the
ClockEvent
returned by it. This ensures that you can call the event
multiple times but it won’t be scheduled more than once. This is not the case
with CyClockBase.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
event = Clock.create_trigger(my_callback)
event()
event()
# will also run the callback only once before the next frame
event = Clock.schedule_once(my_callback) # now it's already scheduled
event() # won't be scheduled again
event()
In addition, it is more convenient to create and bind to
the triggered event than using CyClockBase.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.
Unscheduling¶
An event scheduled with CyClockBase.schedule_once()
,
CyClockBase.schedule_interval()
, or with
CyClockBase.create_trigger()
and then triggered can be unscheduled in
multiple ways. E.g:
def my_callback(dt):
pass
# call my_callback every 0.5 seconds
event = Clock.schedule_interval(my_callback, 0.5)
# call my_callback in 5 seconds
event2 = Clock.schedule_once(my_callback, 5)
event_trig = Clock.create_trigger(my_callback, 5)
event_trig()
# unschedule using cancel
event.cancel()
# unschedule using Clock.unschedule
Clock.unschedule(event2)
# unschedule using Clock.unschedule with the callback
# NOT RECOMMENDED
Clock.unschedule(my_callback)
The best way to unschedule a callback is with ClockEvent.cancel()
.
CyClockBase.unschedule()
is mainly an alias for that for that function.
However, if the original callback itself is passed to
CyClockBase.unschedule()
, it’ll unschedule all instances of that
callback (provided all
is True, the default, otherwise only the first match
is removed).
Calling CyClockBase.unschedule()
on the original callback is highly
discouraged because it’s significantly slower than when using the event.
Clock Lifecycle¶
Kivy’s clock has a lifecycle. By default, scheduling a callback after the Clock has ended will not raise an error, even though the callback may never be called. That’s because most callbacks are like services, e.g. responding to a user button press - if the app is running the callbacks need to service the app and respond to the input, but once the app has stopped or is stopping, we can safely not process these events.
Other events always need to be processed. E.g. another thread may request a callback in kivy’s thread and then process some result. If the event is not processed in Kivy’s thread because the app stopped, the second thread may block forever hanging the application as it exits.
Consequently, we provide a API
(CyClockBase.create_lifecycle_aware_trigger()
) for scheduling callbacks
that raise a ClockNotRunningError
if the clock has stopped. If the
scheduling succeeded it guarantees that one of its callbacks will be called.
I.e. the new CyClockBase.create_lifecycle_aware_trigger()
accepts an
additional clock_ended_callback
parameter. Normally, callback
will be
called when the event is processed. But, if the clock is stopped before it can
be processed, if the application exited normally (and the app was started) and
the event wasn’t canceled, and the callbacks are not garbage collected, then
clock_ended_callback
will be called instead when the clock is stopped.
That is, given these conditions, if ClockNotRunningError
was not
raised when the event was scheduled, then one of these callbacks will be
called - either callback
if the event executed normally, or
clock_ended_callback
if the clock is stopped while the event is scheduled.
By default, events can be scheduled before the clock is started because it is
assumed the clock will eventually be started when the app starts. I.e.
calling CyClockBase.create_lifecycle_aware_trigger()
before the clock
and application starts will succeed. But if the app never actually starts, then
neither of the callbacks may be executed.
New in version 2.0.0: The lifecycle was added in 2.0.0
Exception Handling¶
Kivy provides a exception handling manager,
ExceptionManager
, to handle its internal exceptions
including exceptions raised by clock callbacks, without crashing the
application. By default when an exception is raised, the app will crash.
But, if a handler is registered with the exception manager and the handler
handles the exception, the app will not crash and will continue as normal.:
from kivy.base import ExceptionHandler, ExceptionManager
class MyHandler(ExceptionHandler):
def handle_exception(self, inst):
if isinstance(inst, ValueError):
Logger.exception('ValueError caught by MyHandler')
return ExceptionManager.PASS
return ExceptionManager.RAISE
ExceptionManager.add_handler(MyHandler())
Then, all ValueError exceptions will be logged to the console and ignored. Similarly, if a scheduled clock callback raises a ValueError, other clock events will still be processed normally.
If an event’s callback raises an exception, before the exception handler is executed, the callback is immediately canceled.
It still is possible for the app to be corrupted if kivy itself is the source of the exception. I.e. even with a handler that ignores exceptions and doesn’t crash, the app may be in a corrupted state if the error originates from within Kivy itself. However, the exception handler can help protect the app from crashing and can help protect against user callbacks crashing the app.
Changed in version 2.0.0: Prior to Kivy 2.0.0, an exception raised in a event’s callback would
cause the clock to crash and subsequent events may or may not be executed.
Even if the exception was handled by an
ExceptionHandler
, there was no guarantee that some
scheduled events would not be skipped.
From 2.0.0 onward, if a event’s exception is handled by an
ExceptionHandler
, other events will be shielded from
the exception and will execute normally.
Scheduling from __del__
¶
It is not safe to schedule Clock events from a object’s __del__
or
__dealloc__
method. If you must schedule a Clock call from this method, use
CyClockBase.schedule_del_safe()
or
CyClockBase.schedule_lifecycle_aware_del_safe()
instead.
Threading and Callback Order¶
Beginning with 1.10.0, all the events scheduled for the same frame, e.g.
all the events scheduled in the same frame with a timeout
of 0
,
well be executed in the order they were scheduled.
Also, all the scheduling and canceling methods are fully thread safe and can be safely used from external threads.
As a a consequence, calling CyClockBase.unschedule()
with the original
callback is now significantly slower and highly discouraged. Instead, the
returned events should be used to cancel. As a tradeoff, all the other methods
are now significantly faster than before.
Advanced Clock Details¶
The following section goes into the internal kivy clock details as well as the various clock options. It is meant only for advanced users.
Fundamentally, the Kivy clock attempts to execute any scheduled callback
rhythmically as determined by the specified fps (frame per second, see
maxfps
in config
). That is, ideally, given e.g. a desired fps
of 30, the clock will execute the callbacks at intervals of 1 / 30 seconds, or
every 33.33 ms. All the callbacks in a frame are given the same timestamp,
i.e. the dt
passed to the callback are all the same and it’s the difference
in time between the start of this and the previous frame.
Because of inherent indeterminism, the frames do not actually occur exactly
at intervals of the fps and dt
may be under or over the desired fps.
Also, once the timeout is “close enough” to the desired timeout, as determined
internally, Kivy will execute the callback in the current frame even when the
“actual time” has not elapsed the timeout
amount.
Kivy offers now, since 1.10.0
, multiple clocks with different behaviors.
Default Clock¶
The default clock (default
) behaves as described above. When a callback
with a timeout of zero or non-zero is scheduled, they are executed at the frame
that is near the timeout, which is a function of the fps. So a timeout of zero
would still result in a delay of one frame or about 1 / fps, typically a bit
less but sometimes more depending on the CPU usage of the other events
scheduled for that frame.
In a test using a fps of 30, a callback with a timeout of 0, 0.001, and 0.05, resulted in a mean callback delay of 0.02487, 0.02488, and 0.05011 seconds, respectively. When tested with a fps of 600 the delay for 0.05 was similar, except the standard deviation was reduced resulting in overall better accuracy.
Interruptible Clock¶
The default clock suffers from the quantization problem, as frames occur only on intervals and any scheduled timeouts will not be able to occur during an interval. For example, with the timeout of 0.05, while the mean was 0.05011, its values ranged between 0.02548 - 0.07348 and a standard deviation of 0.002. Also, there’s the minimum timeout of about 0.02487.
The interruptible clock (interrupt
) will execute timeouts even during a
frame. So a timeout of zero will execute as quickly as possible and similarly
a non-zero timeout will be executed even during the interval.
This clock, and all the clocks described after this have an option,
ClockBaseInterruptBehavior.interupt_next_only
. When True, any of the
behavior new behavior will only apply to the callbacks with a timeout of
zero. Non-zero timeouts will behave like in the default clock. E.g. for this
clock when True, only zero timeouts will execute during the the interval.
In a test using a fps of 30, a callback with a timeout of 0, 0.001, and 0.05,
resulted in a mean callback delay of 0.00013, 0.00013, and 0.04120 seconds,
respectively when ClockBaseInterruptBehavior.interupt_next_only
was
False. Also, compared to the default clock the standard deviation was reduced.
When ClockBaseInterruptBehavior.interupt_next_only
was True, the values
were 0.00010, 0.02414, and 0.05034, respectively.
Free Clock¶
The interruptible clock may not be ideal for all cases because all the events are executed during the intervals and events are not executed anymore rhythmically as multiples of the fps. For example, there may not be any benefit for the graphics to update in a sub-interval, so the additional accuracy wastes CPU.
The Free clock (free_all
) solves this by having Clock.xxx_free
versions
of all the Clock scheduling methods. By free, we mean the event is free from
the fps because it’s not fps limited. E.g.
CyClockBaseFree.create_trigger_free()
corresponds to
CyClockBase.create_trigger()
. Only when an event scheduled using the
Clock.xxx_free
methods is present will the clock interrupt and execute
the events during the interval. So, if no free
event is present the clock
behaves like the default
clock, otherwise it behaves like the interrupt
clock.
In a test using a fps of 30, a callback with a timeout of 0s, 0.001s, and 0.05s, resulted in a mean callback delay of 0.00012s, 0.00017s, and 0.04121s seconds, respectively when it was a free event and 0.02403s, 0.02405s, and 0.04829s, respectively when it wasn’t.
Free Only Clock¶
The Free clock executes all events when a free event was scheduled. This results in normal events also being execute in the middle of the interval when a free event is scheduled. For example, above, when a free event was absent, a normal event with a 0.001s timeout was delayed for 0.02405s. However, if a free event happened to be also scheduled, the normal event was only delayed 0.00014s, which may be undesirable.
The Free only clock (free_only
) solves it by only executing free events
during the interval and normal events are always executed like with the
default clock. For example, in the presence of a free event, a normal event
with a timeout of 0.001s still had a delay of 0.02406. So this clock,
treats free and normal events independently, with normal events always being
fps limited, but never the free events.
Summary¶
The kivy clock type to use can be set with the kivy_clock
option the
config
. If KIVY_CLOCK
is present in the environment it
overwrites the config selection. Its possible values are as follows:
When
kivy_clock
isdefault
, the normal clock,ClockBase
, which limits callbacks to the maxfps quantization - is used.When
kivy_clock
isinterrupt
, a interruptible clock,ClockBaseInterrupt
, which doesn’t limit any callbacks to the maxfps - is used. Callbacks will be executed at any time.When
kivy_clock
isfree_all
, a interruptible clock,ClockBaseFreeInterruptAll
, which doesn’t limit any callbacks to the maxfps in the presence of free events, but in their absence it limits events to the fps quantization interval - is used.When
kivy_clock
isfree_only
, a interruptible clock,ClockBaseFreeInterruptAll
, which treats free and normal events independently; normal events are fps limited while free events are not - is used.
Async clock support¶
New in version 2.0.0.
Experimental async support has been added in 2.0.0. The Clock now has a
ClockBaseBehavior.async_tick()
and ClockBaseBehavior.async_idle()
coroutine method which is used by the kivy EventLoop when the kivy EventLoop is
executed in a asynchronous manner. When used, the kivy clock does not
block while idling.
The async library to use is selected with the KIVY_EVENTLOOP environmental
variable or by calling init_async_lib()
directly. The library can be one of “asyncio” when the standard library
asyncio should be used, or “trio” if the trio library
should be used. If not set it defaults to “asyncio”.
See app
for example usage.
- kivy.clock.Clock: kivy.clock.ClockBase = None¶
The kivy Clock instance. See module documentation for details.
- class kivy.clock.ClockBase(**kwargs)[source]¶
Bases:
kivy.clock.ClockBaseBehavior
,kivy._clock.CyClockBase
The
default
kivy clock. See module for details.
- class kivy.clock.ClockBaseBehavior(async_lib='asyncio', **kwargs)[source]¶
Bases:
builtins.object
The base of the kivy clock.
- Parameters
- async_lib: string
The async library to use when the clock is run asynchronously. Can be one of, “asyncio” when the standard library asyncio should be used, or “trio” if the trio library should be used.
It defaults to ‘asyncio’ or the value in the environmental variable KIVY_EVENTLOOP if set.
init_async_lib()
can also be called directly to set the library.
- MIN_SLEEP = 0.005¶
The minimum time to sleep. If the remaining time is less than this, the event loop will continue.
- property frames¶
Number of internal frames (not necessarily drawed) from the start of the clock.
New in version 1.8.0.
- property frames_displayed¶
Number of displayed frames from the start of the clock.
- property 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.
- init_async_lib(lib)[source]¶
Manually sets the async library to use internally, when running in a asynchronous manner.
This can be called anytime before the kivy event loop has started, but not once the kivy App is running.
- Parameters
- lib: string
The async library to use when the clock is run asynchronously. Can be one of, “asyncio” when the standard library asyncio should be used, or “trio” if the trio library should be used.
- class kivy.clock.ClockBaseFreeInterruptAll(**kwargs)[source]¶
Bases:
kivy.clock.ClockBaseInterruptFreeBehavior
,kivy._clock.CyClockBaseFree
The
free_all
kivy clock. See module for details.
- class kivy.clock.ClockBaseFreeInterruptOnly(**kwargs)[source]¶
Bases:
kivy.clock.ClockBaseInterruptFreeBehavior
,kivy._clock.CyClockBaseFree
The
free_only
kivy clock. See module for details.
- class kivy.clock.ClockBaseInterrupt(interupt_next_only=False, **kwargs)[source]¶
Bases:
kivy.clock.ClockBaseInterruptBehavior
,kivy._clock.CyClockBase
The
interrupt
kivy clock. See module for details.
- class kivy.clock.ClockBaseInterruptBehavior(interupt_next_only=False, **kwargs)[source]¶
Bases:
kivy.clock.ClockBaseBehavior
A kivy clock which can be interrupted during a frame to execute events.
- init_async_lib(lib)[source]¶
Manually sets the async library to use internally, when running in a asynchronous manner.
This can be called anytime before the kivy event loop has started, but not once the kivy App is running.
- Parameters
- lib: string
The async library to use when the clock is run asynchronously. Can be one of, “asyncio” when the standard library asyncio should be used, or “trio” if the trio library should be used.
- class kivy.clock.ClockBaseInterruptFreeBehavior(**kwargs)[source]¶
Bases:
kivy.clock.ClockBaseInterruptBehavior
A base class for the clock that interrupts the sleep interval for free events.
- class kivy.clock.ClockEvent(CyClockBase clock, int loop, callback, double timeout, double starttime, cid=None, int trigger=False, clock_ended_callback=None, release_ref=True, **kwargs)¶
Bases:
builtins.object
This class is never created by the user; instead, kivy creates and returns an instance of this class when scheduling a callback.
An event can be triggered (scheduled) by calling it. If it’s already scheduled, nothing will happen, otherwise it’ll be scheduled. E.g.:
event = Clock.schedule_once(my_callback, .5) event() # nothing will happen since it's already scheduled. event.cancel() # cancel it event() # now it's scheduled again.
- callback¶
callback: object
- cancel()¶
Cancels the callback if it was scheduled to be called. If not scheduled, nothing happens.
- cid¶
cid: object
- clock¶
clock: kivy._clock.CyClockBase The
CyClockBase
instance associated with the event.
- clock_ended_callback¶
clock_ended_callback: object A Optional callback for this event, which if provided is called by the clock
when the clock is stopped and the event was not ticked.
- get_callback()¶
Returns the callback associated with the event. Callbacks get stored with a indirect ref so that it doesn’t keep objects alive. If the callback is dead, None is returned.
- get_clock_ended_callback()¶
Returns the clock_ended_callback associated with the event. Callbacks get stored with a indirect ref so that it doesn’t keep objects alive. If the callback is dead or wasn’t provided, None is returned.
- is_triggered¶
Returns whether the event is scheduled to have its callback executed by the kivy thread.
- next¶
next: kivy._clock.ClockEvent The next
ClockEvent
in order they were scheduled.
- prev¶
prev: kivy._clock.ClockEvent The previous
ClockEvent
in order they were scheduled.
- release()¶
(internal method) Converts the callback into a indirect ref.
- release_ref¶
release_ref: ‘int’ If True, the event should never release the reference to the callbacks.
If False, a weakref may be created instead.
- tick(double curtime)¶
(internal method) Processes the event for the kivy thread.
- timeout¶
timeout: ‘double’ The duration after scheduling when the callback should be executed.
- weak_callback¶
weak_callback: object
- weak_clock_ended_callback¶
weak_clock_ended_callback: object
- exception kivy.clock.ClockNotRunningError¶
Bases:
RuntimeError
Raised by the kivy Clock when scheduling an event if the Kivy Clock has already finished (
stop_clock
was called).
- class kivy.clock.CyClockBase(**kwargs)¶
Bases:
builtins.object
- clock_resolution¶
clock_resolution: ‘double’ If the remaining time until the event timeout is less than
clock_resolution
,the clock will execute the callback even if it hasn’t exactly timed out.
If -1, the default, the resolution will be computed from config’s
maxfps
. Otherwise, the provided value is used. Defaults to -1.
- create_lifecycle_aware_trigger(callback, clock_ended_callback, timeout=0, interval=False, release_ref=True) ClockEvent ¶
Create a Trigger event similarly to
create_trigger()
, but the event is sensitive to the clock’s state.If this event is triggered after the clock has stopped (
stop_clock()
), then aClockNotRunningError
will be raised. If the error is not raised, then eithercallback
orclock_ended_callback
will be called.callback
will be called when the event is normally executed. If the clock is stopped before it can be executed, provided the app exited normally without crashing and the event wasn’t manually canceled, and the callbacks are not garbage collected thenclock_ended_callback
will be called instead when the clock is stopped.- Parameters
- callback: callable
The callback to execute from kivy. It takes a single parameter - the current elapsed kivy time.
- clock_ended_callback: callable
A callback that will be called if the clock is stopped while the event is still scheduled to be called. The callback takes a single parameter - the event object. When the event is successfully scheduled, if the app exited normally and the event wasn’t canceled, and the callbacks are not garbage collected - it is guaranteed that either
callback
orclock_ended_callback
would have been called.- timeout: float
How long to wait before calling the callback.
- interval: bool
Whether the callback should be called once (False) or repeatedly with a period of
timeout
(True) likeschedule_interval()
.- release_ref: bool
If True, the default, then if
callback
orclock_ended_callback
is a class method and the object has no references to it, then the object may be garbage collected and the callbacks won’t be called. If False, the clock keeps a reference to the object preventing it from being garbage collected - so it will be called.
- Returns
A
ClockEvent
instance. To schedule the callback of this instance, you can call it.
New in version 2.0.0.
- create_trigger(callback, timeout=0, interval=False, release_ref=True) ClockEvent ¶
Create a Trigger event. It is thread safe but not
__del__
or__dealloc__
safe (seeschedule_del_safe()
). Check module documentation for more information.To cancel the event before it is executed, call
ClockEvent.cancel()
on the returned event. To schedule it again, simply call the event (event()
) and it’ll be safely rescheduled if it isn’t already scheduled.- Parameters
- callback: callable
The callback to execute from kivy. It takes a single parameter - the current elapsed kivy time.
- timeout: float
How long to wait before calling the callback.
- interval: bool
Whether the callback should be called once (False) or repeatedly with a period of
timeout
(True) likeschedule_interval()
.- release_ref: bool
If True, the default, then if
callback
is a class method and the object has no references to it, then the object may be garbage collected and the callbacks won’t be called. If False, the clock keeps a reference to the object preventing it from being garbage collected - so it will be called.
- Returns
A
ClockEvent
instance. To schedule the callback of this instance, you can call it.
New in version 1.0.5.
Changed in version 1.10.0:
interval
has been added.Changed in version 2.0.0:
release_ref
has been added.
- get_events()¶
Returns the list of
ClockEvent
instances currently scheduled.
- get_min_timeout()¶
Returns the remaining time since the start of the current frame for the event with the smallest timeout.
- get_resolution()¶
Returns the minimum resolution the clock has. It’s a function of
clock_resolution
andmaxfps
provided at the config.
- handle_exception(e)¶
Provides an opportunity to handle an event’s exception.
If desired, the exception is handled, otherwise it should be raised again. By default it is raised again.
- Parameters
e – The exception to be handled.
New in version 2.0.0.
- has_ended¶
has_ended: ‘int’
- max_iteration¶
max_iteration: ‘int’ The maximum number of callback iterations at the end of the frame, before the next
frame. If more iterations occur, a warning is issued.
- on_schedule(event)¶
Function that is called internally every time an event is triggered for this clock. It takes the event as a parameter.
The order of
on_schedule
calls are not guaranteed to be in the same order that the events are scheduled. Similarly, it is possible that the event being scheduled was canceled before this is called on the event. That’s becauseon_schedule()
may be called from different threads.
- schedule_del_safe(callback)¶
Schedule a callback that is thread safe and
__del__
or__dealloc__
safe.It’s unsafe to call various kinds of code from
__del__
or__dealloc__
methods because they can be executed at any time. Most Kivy’s Clock methods are unsafe to call the Clock from these methods. Instead, use this method, which is thread safe and__del__
or__dealloc__
safe, to schedule the callback in the kivy thread. It’ll be executed in order after the normal events are processed.- Parameters
- callback: Callable
The callback the execute from kivy. It takes no parameters and cannot be canceled.
New in version 1.11.0.
- schedule_interval(callback, timeout) ClockEvent ¶
Schedule an event to be called every <timeout> seconds. See
create_trigger()
for advanced scheduling and more details.To cancel the event before it is executed, call
ClockEvent.cancel()
on the returned event. If the callback is a class method, a weakref to the object is created and it may be garbage collected if there’s no other reference to the object.- Returns
A
ClockEvent
instance. As opposed tocreate_trigger()
which only creates the trigger event, this method also schedules it.
- schedule_lifecycle_aware_del_safe(callback, clock_ended_callback)¶
Schedule a callback that is thread safe and
__del__
or__dealloc__
safe similarly toschedule_del_safe()
, but the callback is sensitive to the clock’s state.If this event is triggered after the clock has stopped (
stop_clock()
), then aClockNotRunningError
will be raised. If the error is not raised, then eithercallback
orclock_ended_callback
will be called.callback
will be called when the callback is normally executed. If the clock is stopped before it can be executed, provided the app exited normally without crashing thenclock_ended_callback
will be called instead when the clock is stopped.- Parameters
- callback: Callable
The callback the execute from kivy. It takes no parameters and cannot be canceled.
- clock_ended_callback: callable
A callback that will be called if the clock is stopped while the callback is still scheduled to be called. The callback takes a single parameter - the callback. If the app exited normally, it is guaranteed that either
callback
orclock_ended_callback
would have been called.
New in version 2.0.0.
- schedule_once(callback, timeout=0) ClockEvent ¶
Schedule an event in <timeout> seconds. If <timeout> is unspecified or 0, the callback will be called after the next frame is rendered. See
create_trigger()
for advanced scheduling and more details.To cancel the event before it is executed, call
ClockEvent.cancel()
on the returned event. If the callback is a class method, a weakref to the object is created and it may be garbage collected if there’s no other reference to the object.- 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()
).
- start_clock()¶
Must be called to start the clock.
Once
stop_clock()
is called, it cannot be started again.
- stop_clock()¶
Stops the clock and cleans up.
This must be called to process the lifecycle_aware callbacks etc.
- unschedule(callback, all=True)¶
Remove a previously scheduled event.
An
ClockEvent
can also be canceled directly by callingClockEvent.cancel()
.- 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 was scheduled.
Warning
Passing the callback function rather than the returned
ClockEvent
will result in a significantly slower unscheduling.- 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.
- callback:
Changed in version 1.9.0: The all parameter was added. Before, it behaved as if all was True.
- class kivy.clock.CyClockBaseFree¶
Bases:
kivy._clock.CyClockBase
A clock class that supports scheduling free events in addition to normal events.
Each of the
create_trigger()
,schedule_once()
, andschedule_interval()
methods, which create a normal event, have a corresponding method for creating a free event.- create_lifecycle_aware_trigger(callback, clock_ended_callback, timeout=0, interval=False, release_ref=True) FreeClockEvent ¶
- create_lifecycle_aware_trigger_free(callback, clock_ended_callback, timeout=0, interval=False, release_ref=True) FreeClockEvent ¶
Similar to
create_lifecycle_aware_trigger()
, but instead creates a free event.
- create_trigger(callback, timeout=0, interval=False, release_ref=True) FreeClockEvent ¶
- create_trigger_free(callback, timeout=0, interval=False, release_ref=True) FreeClockEvent ¶
Similar to
create_trigger()
, but instead creates a free event.
- get_min_free_timeout()¶
Returns the remaining time since the start of the current frame for the free event with the smallest timeout.
- schedule_interval(callback, timeout) FreeClockEvent ¶
- schedule_interval_free(callback, timeout) FreeClockEvent ¶
Similar to
schedule_interval()
, but instead creates a free event.
- schedule_once(callback, timeout=0) FreeClockEvent ¶
- schedule_once_free(callback, timeout=0) FreeClockEvent ¶
Similar to
schedule_once()
, but instead creates a free event.
- class kivy.clock.FreeClockEvent(free, *largs, **kwargs)¶
Bases:
kivy._clock.ClockEvent
CyClockBaseFree
. It stores whether the event was scheduled as a free event.- free¶
free: ‘int’ Whether this event was scheduled as a free event.
- 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 succeeded!', 'This callback is called in the main thread.') self.req = UrlRequest(url='http://...', on_success=callback)
New in version 1.8.0.