2016-08-18 35 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() 
相關問題