python - 如何在 python 3.4 中调用方法并使其在后台运行?

标签 python python-3.x google-cloud-messaging python-asyncio

我已经用 python 实现了 Google Cloud Messaging 服务器,我希望该方法是异步的。我不期望该方法有任何返回值。有没有一种简单的方法可以做到这一点? 我尝试使用 asyncio 包中的 async:

...
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!")

最佳答案

您可以使用 ThreadPoolExecutor :

from concurrent.futures import ThreadPoolExecutor

def send_notification(module_name, module_status):
    [...]

with ThreadPoolExecutor() as executor:
    future = executor.submit(send_notification, module_name, module_status)

关于python - 如何在 python 3.4 中调用方法并使其在后台运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39025511/

相关文章:

python - 单击 Scrapy-Splash 中的按钮

python - pip install --upgrade sqlalchemy 超出最大递归深度

python - Ubuntu Oneiric 上的 scikits.audiolab - ImportError : No module named _sndfile

python - 如何将字符串传递给 subprocess.Popen(使用 stdin 参数)?

python - 将代码从当前文件复制到另一个Python文件

java - 无法解析 : com. google.android.gms :play-services-gcm:7. 5.+

android - 为 'Package Name' 重置退避

python-3.x - 当查询包含来自多个数据库的表的连接时,如何在 boto3 中设置 QueryExecutionContext?

python - 使用 python 和 selenium 登录网站

android - GCM,用户通知,同一设备上的两个 GCM 感知应用程序,当 GCM 消息与通知 key 一起发送时触发哪个应用程序?