6

I am writing a python program which I would run using supervisor. The program basically does the following:

if __name__ == "__main__":
    while True:
        run()

where run function does a simple task of getting something from database (mysqlDB) and send that in an email.

I want to write the program such that when I use

supervisorctl stop program

the mysql connection should close and a propper log for shutdown is done.

Is there any way I can handle the stop command in my python script.

Siddharth Gupta
  • 1,573
  • 9
  • 24

1 Answers1

0

You can use the signal unit to receive signals from the OS, which is what supervisor will do. Example code below is NOT tested. At all.

import signal

keep_going = True

def my_shutdown_handler(signum, frame):
    # set a flag to exit your loop or call what you need to exit gracefully
    keep_going = False

if __name__ == "__main__":
    signal.signal(signal.SIGTERM, my_shutdown_handler) 
    while keep_going:
        run()

See more and much cleaner examples here:

How to process SIGTERM signal gracefully?

Eric G
  • 3,427
  • 5
  • 28
  • 52