Implement delay callback common function in Python

Source: Internet
Author: User
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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.