user2290820
user2290820

Reputation: 2759

Run gevent processes and server concurrently

How to run a given module given I want to run some functions concurrently that are not necessarily using routing (could be daemon services) while at the same time running the app server?

For example:

#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'

Do I have to use the above like this after main ?

gevent.joinall(gevent.spawn(alarm))

app.run(....)

or

gevent.joinall((gevent.spawn(alarm),gevent.spawn(app.run)))

The objective is run these alarm like daemon services, do their work and snooze while rest of service operations work as usual. The server should start concurrently as well. correct me if im not on the right track.

Upvotes: 4

Views: 1963

Answers (1)

czardoz
czardoz

Reputation: 1147

Gevent comes with it's own WSGI servers, so it is really not necessary to use app.run. The servers are:

Both provide the same interface.

You can use these to achieve what you want:

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'

Upvotes: 5

Related Questions