This article mainly introduces to you about the implementation of the delay callback common functions in Python, the text through the example code introduced in very detailed, to everyone's study or work has a certain reference learning value, need to friends below with small to learn together.
Objective
The callback function is a problem that we often encounter in Python programming, and we want to make a function callback at some point in the future, which can be implemented using a call_later() function, the first parameter is the call delay, the second is the function name of the callback.
Examples are as follows:
Import Asyncio def callback (n): print (' callback {} invoked '. Format (n)) async def Main (loop): print (' Registering callbacks ') Loop.call_later (0.2, callback, 1) Loop.call_later (0.1, Callback, 2) Loop.call _soon (callback, 3) await Asyncio.sleep (0.4) Event_loop = Asyncio.get_event_loop () Try: print (' Entering event loop ') Event_loop.run_until_complete (Main (Event_loop)) Finally: print (' Closing event loop ') ) Event_loop.close ()
The resulting output is as follows:
Entering event loopregistering Callbackscallback 3 invokedcallback 2 invokedcallback 1 invokedclosing event loop
In this example, the three functions that are called at the same time will find that the order of the calls is different. call_soon()is called immediately after registration.