Repository navigation
Expand file tree
/
Copy pathworker.py
More file actions
52 lines (38 loc) · 1.38 KB
/
Copy pathworker.py
File metadata and controls
52 lines (38 loc) · 1.38 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
"""
worker.py
Entry point for a Render Background Worker. Calls into main.call_api() on
a loop, with graceful shutdown on SIGTERM/SIGINT (Render sends SIGTERM when
stopping or redeploying a worker, so we want to exit cleanly rather than
get killed mid-request).
"""
import os
import signal
import sys
import time
from main import call_api
POLL_INTERVAL_SECONDS = int(os.environ.get("POLL_INTERVAL_SECONDS", "3600"))
_running = True
def _handle_shutdown(signum, frame):
global _running
print(f"Received signal {signum}, shutting down gracefully...", flush=True)
_running = False
signal.signal(signal.SIGTERM, _handle_shutdown)
signal.signal(signal.SIGINT, _handle_shutdown)
def main_loop():
print(f"Worker started. Calling API every {POLL_INTERVAL_SECONDS}s.", flush=True)
while _running:
try:
call_api("Hello! Just testing the API connection.")
except Exception as exc:
print(f"Error calling API: {exc}", flush=True)
# Sleep in short increments so a shutdown signal is handled promptly
# instead of waiting out the full interval.
slept = 0
while slept < POLL_INTERVAL_SECONDS and _running:
chunk = min(5, POLL_INTERVAL_SECONDS - slept)
time.sleep(chunk)
slept += chunk
print("Worker stopped.", flush=True)
sys.exit(0)
if __name__ == "__main__":
main_loop()