从另一个方法异步调用方法

时间:2016-03-11 16:22:42

标签: python asynchronous

我有一个collect_data方法,可以从另一个方法create调用。我想异步调用这个collect_data方法,因为用户不需要等待函数create的响应。

 def create(obj):
     "do something in database"
     "return ID for newly created data in DB"
     collect_data(obj, newly_created_id)
     return newly_created_id

 def collect_data(obj, newly_created_id):
     "collect data from other methods."
     "Put the data in MQ."

所以,我想异步运行这个collect_data,这样用户就不需要等待new_created_id,直到数据放入ActiveMQ。

我尝试过多处理,如下所示。

 import multiprocessing as mp
 def create(obj):
     pool = mp.Pool()
     "do something in database"
     "return ID for newly created data in DB"
     pool.apply_async(collect_data, args=(obj, newly_created_id))
     return newly_created_id

但这似乎不是异步运行的。为了测试我在collect_data中插入了2分钟的睡眠。函数create没有立即返回new_created_id。

有人可以帮忙。

1 个答案:

答案 0 :(得分:1)

from multiprocessing import Pool
import time
import random

class DATA:
    def __init__(self, obj, new_id):
        self.obj = obj
        self.new_id = new_id

def collect_id(data):
    print 'collecting data for obj {0} with id {1}'.format(data.obj, data.new_id)

def create(obj):
    pool = Pool()
    # "do something in database"
    # "return ID for newly created data in DB"
    newly_created_id = int(random.random()*10)
    data = DATA(obj, newly_created_id)
    r  = pool.map_async(collect_id, [data])
    return newly_created_id


new_id = create({'some':'object'})
print "new id: {0}".format(new_id)

您会看到它输出ID之前输出它正在收集数据,显示其在后台发生异步