0

For example, I'm writing a basic wsgi server program.

This program runs perfectly but the server will keeping running until I press Ctrl-C. I want the program to exit when the server has been running for 10 minutes.

And I've tried create a process to exit the program, but I think that's not required, and it doesn't work:

import time
import sys
from multiprocessing import Process
from wsgiref.simple_server import make_server
def application(environ, start_response):
    start_response('200 OK', [('Content-Type', 'text/html')])
    return [b'Hello']

def p_exit():
    time.sleep(600) 
    sys.exit()


p = Process(target=p_exit)
p.start()

httpd = make_server('', 80, application)
httpd.serve_forever()
Casimir Crystal
  • 18,651
  • 14
  • 55
  • 76

1 Answers1

2

You can set an alarm signal handler to exit, and trigger the alarm in 10 minutes:

def handler(*args):
    sys.exit(1)

signal.signal(signal.SIGALRM, handler)
signal.alarm(60*10)

# Now start the wsgi application and wait
httpd = make_server('', 80, application)
httpd.serve_forever()

However, ALRM signal is *nix only, for Windows systems, you need to try something like this.

Community
  • 1
  • 1
NeoWang
  • 13,687
  • 19
  • 61
  • 112