如果我想同时运行一些不一定使用路由(可能是守护程序服务)的功能,同时运行应用服务器,如何运行给定的模块?
例如:
#some other route functions app.post(...)
#some other concurrent functions
def alarm():
'''
Run this service every X duration
'''
ALARM = 21
try:
while 1:
#checking time and doing something. Then finding INTERVAL
gevent.sleep(INTERVAL)
except KeyboardInterrupt,e:
print 'exiting'
我必须在 main 之后像这样使用上面的内容吗?
gevent.joinall(gevent.spawn(alarm))
app.run(....)
或
gevent.joinall((gevent.spawn(alarm),gevent.spawn(app.run)))
目标是像守护进程服务一样运行这些警报,完成它们的工作并暂停,而其余的服务操作照常工作。 服务器也应该同时启动。如果我不在正确的轨道上,请纠正我。
最佳答案
Gevent 自带 WSGI 服务器,所以真的没有必要使用 app.run
。服务器是:
两者提供相同的接口(interface)。
您可以使用这些来实现您想要的:
import gevent
import gevent.monkey
gevent.monkey.patch_all()
import requests
from gevent.pywsgi import WSGIServer
# app = YourBottleApp
def alarm():
'''
Run this service every X duration
'''
ALARM = 21
while 1:
#checking time and doing something. Then finding INTERVAL
gevent.sleep(INTERVAL)
if __name__ == '__main__':
http_server = WSGIServer(('', 8080), app)
srv_greenlet = gevent.spawn(http_server.serve_forever)
alarm_greenlet = gevent.spawn(alarm)
try:
gevent.joinall([srv_greenlet, alarm_greenlet])
except KeyboardInterrupt:
http_server.stop()
print 'Quitting'
关于python - 同时运行gevent进程和服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24019259/