Python Asynchronous Task Queue example

Source: Internet
Author: User
Many scenarios require an asynchronous callback mechanism for non-blocking. This is a simple example, please refer to the use of it

Copy CodeThe code is as follows:


#!/usr/bin/env python
#-*-Coding:utf-8-*-

Import logging
Import queue
Import threading

Def func_a (A, B):
Return a + b

Def func_b ():
Pass

Def Func_c (A, B, c):
Return a, B, c

# Asynchronous Task Queue
_task_queue = queue. Queue ()

Def async_call (function, callback, *args, **kwargs):
_task_queue.put ({
' function ': function,
' Callback ': Callback,
' args ': args,
' Kwargs ': Kwargs
})

Def _task_queue_consumer ():
"""
Asynchronous Task Queue Consumer
"""
While True:
Try
task = _task_queue.get ()
function = Task.get (' function ')
callback = Task.get (' callback ')
args = Task.get (' args ')
Kwargs = Task.get (' Kwargs ')
Try
If callback:
Callback (function (*args, **kwargs))
Except Exception as ex:
If callback:
Callback (ex)
Finally
_task_queue.task_done ()
Except Exception as ex:
Logging.warning (ex)

def handle_result (Result):
Print (Type (result), result)

if __name__ = = ' __main__ ':
t = Threading. Thread (Target=_task_queue_consumer)
T.daemon = True
T.start ()

Async_call (Func_a, Handle_result, 1, 2)
Async_call (Func_b, Handle_result)
Async_call (Func_c, Handle_result, 1, 2, 3)
Async_call (Func_c, Handle_result, 1, 2, 3, 4)

_task_queue.join ()
  • 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.