Signal Handlers For Graceful Shutdown

Register SIGINT and SIGTERM handlers that flip a shutdown flag, letting the worker finish its current job before the process exits cleanly.

PythonResilience

Code

pythonsnippet
24 lines
import signal

shutdown = False


def handle(signum: int, frame: object) -> None:
    global shutdown
    shutdown = True
    print(f'{signal.Signals(signum).name} received, finishing current job')


signal.signal(signal.SIGTERM, handle)
signal.signal(signal.SIGINT, handle)

jobs = ['resize-1', 'resize-2', 'resize-3']
for job in jobs:
    if shutdown:
        print('skipping', job)
        continue
    print('processing', job)
    if job == 'resize-2':
        handle(signal.SIGTERM, None)  # 模拟收到终止信号

print('clean exit, shutdown =', shutdown)

Output

Captured from a sandboxed run of this snippet in the build pipeline.

processing resize-1
processing resize-2
SIGTERM received, finishing current job
skipping resize-3
clean exit, shutdown = True

How the snippet works

Structurally, expect the function handle and nothing else.

One loop does the cycling here: for job in jobs.

Caveats

  • Requires signal as a package; the snippet will not run without it.

Applying it

The main signature reads def handle(signum: int, frame: object) -> None

The demo output is labeled (skipping, processing, clean exit, shutdown =), so every printed line maps back to its originating operation.

Import handle from the file and call it — the rest of the code is implementation detail.

Statements that matter

def handle(signum: int, frame: object) -> None:
    global shutdown
    shutdown = True
    print(f'{signal.Signals(signum).name} received, finishing current job')

Interactive Tools for This Topic

FAQ

Any setup needed beyond the language runtime?
None — the language runtime is the only requirement. Every import resolves inside the standard library — `signal`. The file defines `handle` at load time.