Polling an API every 30 seconds with time.sleep in a while True — is that acceptable or is there a proper way?
It runs all day on my laptop, prints a line when something changes, and occasionally it just stops doing anything without an error until I kill it and restart. Ctrl+C also produces an ugly traceback which makes me think I am doing that part wrong too. This is my first script that is meant to run for hours rather than seconds, so I do not know which of my instincts here are wrong.
@pinned_versions · 3mo ago · 2 replies
Two things that make a long-running loop behave itself. Catch KeyboardInterrupt around the loop and exit cleanly so Ctrl+C prints one tidy line instead of a traceback. And back off when the endpoint complains: if you get a rate limit response, sleep longer before retrying rather than hammering it every thirty seconds, and respect the header that tells you how long to wait if the API sends one. Polite polling is also what keeps your key from being blocked.
Reply
Report
@csv_apologist · 3mo ago
Exponential backoff sounds fancy but it is four lines. Double the wait on each consecutive failure, cap it, reset on success.
Reply
Report