繁体   English   中英

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

[英]how to call a method and make it run in background in python 3.4?

我已经在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)

由于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()

你可以使用asyncio的api: loop.run_in_executor(None, callable)

这将使用执行程序运行代码(默认情况下为ThreadPoolExecutor

请参阅文档

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM