Run certain code every n seconds
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.
Introduction
Running code every n seconds looks trivial until you need reliability under load, graceful shutdown, and error handling. A naive timer can drift, overlap executions, or silently stop after an exception. The right design depends on whether you need best-effort periodic callbacks, strict non-overlapping jobs, or durable scheduled tasks.
Basic Timer Approaches by Runtime
Most runtimes provide built-in periodic scheduling primitives.
JavaScript simple interval:
Python loop:
These are fine for simple scripts, but production jobs need additional control.
Prevent Overlapping Execution
If a job can take longer than interval duration, fixed intervals can create overlap. A safer pattern schedules next run only after current run completes.
This gives non-overlapping behavior and naturally back-pressures slow tasks.
Cancellation and Shutdown Control
Production services need clean stop behavior. In Python, threading.Event is a practical cancellation mechanism.
Cancellation-aware loops are safer than hard sleeps during shutdown.
C# Async Periodic Pattern
In modern .NET, PeriodicTimer offers clear async semantics.
This integrates cleanly with hosted-service cancellation tokens.
Drift, Jitter, and Clock Reality
No in-process timer is perfectly precise. Delay sources include scheduler contention, garbage collection, blocking I O, and machine sleep. If exact cadence matters, compute next target timestamp and adjust wait duration rather than chaining fixed sleeps.
For critical scheduling guarantees, external schedulers or queue systems are often better than in-process loops.
Error Handling and Resilience
Always isolate job exceptions so one failure does not stop the scheduler.
Add retry with backoff for transient remote failures. Without this, periodic jobs can hammer unstable dependencies.
Cron and External Schedulers
If the task is independent and does not need in-process state, cron or a scheduler service may be simpler and more reliable.
External scheduling decouples task cadence from application process uptime.
Monitoring and Operational Signals
Track these metrics for periodic jobs:
- execution duration
- success and failure counts
- delay from planned schedule time
- overlap or skipped runs
Monitoring reveals scheduler stress before users notice missing or delayed background work.
Idempotency for Periodic Jobs
Periodic tasks should be designed as idempotent whenever possible. If a retry or overlapping run happens unexpectedly, idempotent behavior prevents duplicate side effects and data corruption.
Common Pitfalls
- Assuming timer callbacks run at exact intervals under load.
- Allowing overlapping runs when job duration is variable.
- Ignoring cancellation and forcing process shutdown.
- Letting unhandled exceptions terminate periodic loops.
- Using in-process timers for jobs that require durable scheduling guarantees.
Summary
- Periodic execution needs more than a simple interval call in production.
- Use non-overlapping patterns when task duration is unpredictable.
- Add cancellation, error handling, and retry logic.
- Choose external schedulers for durable or process-independent jobs.
- Monitor drift and execution outcomes to keep periodic workflows reliable.
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.