Esegui processi e server Gevent contemporaneamente
Domanda
Come eseguire un determinato modulo dato che voglio eseguire alcune funzioni contemporaneamente che non utilizzano necessariamente l'utilizzo di routing (potrebbero essere servizi demoni) mentre è allo stesso tempo l'esecuzione dell'app Server?
Ad esempio:
#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'
.
Devo usare quanto sopra come questo dopo Main ?
gevent.joinall(gevent.spawn(alarm))
app.run(....)
.
o
gevent.joinall((gevent.spawn(alarm),gevent.spawn(app.run)))
.
L'obiettivo è eseguito questo allarme come i servizi dei demoni, fanno il loro lavoro e snooze mentre il resto delle operazioni di servizio funziona come al solito. Il server dovrebbe iniziare anche in concomitanza.correggimi se non sono sulla strada giusta.
Soluzione
Gevent viene fornito con i propri server WSGI, quindi non è davvero necessario utilizzare app.run
.I server sono:
entrambi forniscono la stessa interfaccia.
Puoi usarli per ottenere ciò che desideri:
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'
.