2016-08-18 36 views
1

我已经在python中实现了Google Cloud Messaging服务器,并且我希望该方法是异步的。我不希望任何来自该方法的返回值。有没有简单的方法来做到这一点? 我一直在使用asyncasyncio包的尝试:如何调用一个方法,并使其在Python 3.4中的后台运行?

... 
loop = asyncio.get_event_loop() 
if(module_status=="Fail"): 
     loop.run_until_complete(sendNotification(module_name, module_status)) 
... 

,这里是我的方法sendNotification()

async def sendNotification(module_name, module_status): 
    gcm = GCM("API_Key") 
    data ={"message":module_status, "moduleName":module_name} 
    reg_ids = ["device_tokens"] 
    response = gcm.json_request(registration_ids=reg_ids, data=data) 
    print("GCM notification sent!") 
+1

如果'gcm.json_request'方法没有使用'asyncio'定义,那么没有简单的方法来做到这一点。 –

+0

@NateMara我正在使用python-gcm librabry [link](https://github.com/geeknam/python-gcm/blob/master/gcm/gcm.py)。我看到它的代码,它不是异步的。你能提出一个解决方案,让我的方法在后台运行吗? – Arjun

+1

你可以使用'multiprocessing'或者使用'aiohttp'自己进行HTTP调用 –

回答

1

你可以使用一个ThreadPoolExecutor

from concurrent.futures import ThreadPoolExecutor 
executor = ThreadPoolExecutor() 
... 
future = executor.submit(send_notification, module_name, module_status) 
1

由于GCM不是异步库兼容需要使用外部事件循环。

有几个,最简单的一个IMO大概是gevent

请注意,如果使用的底层库依赖于阻止行为来操作,gevent monkey修补可能会引入死锁。

import gevent 
from gevent.greenlet import Greenlet 
from gevent import monkey 
monkey.patch_all() 

def sendNotification(module_name, module_status): 
    gcm = GCM("API_Key") 
    data ={"message":module_status, "moduleName":module_name} 
    reg_ids = ["device_tokens"] 
    response = gcm.json_request(registration_ids=reg_ids, data=data) 
    print("GCM notification sent!") 

greenlet = Greenlet.spawn(sendNotification, 
          args=(module_name, module_status,)) 
# Yield control to gevent's event loop without blocking 
# to allow background tasks to run 
gevent.sleep(0) 
# 
# Other code, other greenlets etc here 
# 
# Call get to get return value if needed 
greenlet.get() 
相关问题