Question

I have this methods:

class dJobs():
    def server(self):
        address = ('127.0.0.1', dConfig.cgiport)
        handler = CGIHTTPServer.CGIHTTPRequestHandler
        handler.cgi_directories = ['/cgi-bin']
        self.logger.info("starting http server on port %s" %str(port))
        httpd = BaseHTTPServer.HTTPServer(address, handler)
        httpd.serve_forever()

    def job(self):
        self.runNumber = 0
        while True:
            self.logger.info("Counting: %s" %str(self.runNumber))
            self.runNumber+=1
            time.sleep(1)

I want run job while waiting for http and cgi requests, handle requests and then continue job method. Is it possibile to do this using gevent (and how), or i need to use threading ?

i.e. I want to run both method concurrently without creating threads.

Was it helpful?

Solution

This solution seems to work for me:

  • import monkey:

    from gevent import monkey
    monkey.patch_all(thread=False)
    
  • add and run this method:

    def run(self):
       jobs = [gevent.spawn(self.server),gevent.spawn(self.job)]
       gevent.joinall(jobs)
    

Please try it out in your program.

OTHER TIPS

If your job is CPU-bound, you must not use Python threads because of GIL. Alternative is multiprocessing module.

Also you could use uWSGI--it can do CGI and run jobs. Look at the WSGI which is the main feature of uWSGI, you may want to use that instead of CGI.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top