Created
January 19, 2018 17:27
-
-
Save pyk/e794d774afe4dbefb0958ecc43e7f45d to your computer and use it in GitHub Desktop.
Graceful shutdown in Python While Loop
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import time | |
import signal | |
def busy_work(seconds): | |
print("Start busy_work") | |
time.sleep(seconds) | |
print("Stop busy_work") | |
class Transporter: | |
def __init__(self): | |
self.stopped = False | |
def run(self): | |
while not self.stopped: | |
busy_work(10) | |
def stop(self, signal, frame): | |
print("Stop the transporter ...") | |
self.stopped = True | |
def main(): | |
# Setup transporter | |
transporter = Transporter() | |
# Setup signal handler | |
signal.signal(signal.SIGINT, transporter.stop) | |
signal.signal(signal.SIGTERM, transporter.stop) | |
transporter.run() | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment