简体   繁体   English

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

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

I have implemented the Google Cloud Messaging server in python and I want that method to be Asynchronous. 我已经在python中实现了Google Cloud Messaging服务器,我希望该方法是异步的。 I do not expect any return values from that method. 我不希望该方法返回任何值。 Is there a simple way to do this? 有一个简单的方法吗? I have tried using async from asyncio package: 我尝试过使用asyncio包中的async

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

and here is my method sendNotification() : 这是我的方法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!")

You could use a ThreadPoolExecutor : 你可以使用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)

Since GCM is not async library compatible need to use an external event loop. 由于GCM不兼容异步库需要使用外部事件循环。

There are a few, simplest one IMO is probably gevent . 有一些,最简单的一个IMO可能是gevent

Note that gevent monkey patching may introduce dead locks if the underlying libraries used rely on blocking behaviour to operate. 请注意,如果使用的基础库依赖于阻塞行为来运行,那么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()

You can use asyncio's api: loop.run_in_executor(None, callable) 你可以使用asyncio的api: loop.run_in_executor(None, callable)

This will run the code using an executor (by default a ThreadPoolExecutor ) 这将使用执行程序运行代码(默认情况下为ThreadPoolExecutor

See the documentation 请参阅文档

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

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