From magazine topic to project implementation
Relevant service and technical pages for this post
The classic problem rarely appears in lab tests, but on day three at the customer’s site: a status should update „every 10 seconds“, a timeout should trigger „after 2 minutes“, a progress indicator should advance „per minute“. In development everything seems stable. Then real UI load is added: a large grid is sorted, a report is rendered, a PDF is produced, and Synchronize calls from worker threads run in parallel. And suddenly it’s no longer 10 seconds, but 12, 15 or 30. Anyone who at this point still „counts intervals“ can hardly explain it cleanly — and ends up with drifting logs, implausible time stamps and hard-to-reproduce errors. This is exactly where Timer-Drift vermeiden comes in practically: not through „magical precision timers“, but through precise timestamps, a monotonic time base and an explicit decision about how the application treats delays.
The decision path is simple but important: do you stick with the convenient model „every OnTimer is a tick“ (quick to implement, but systematically prone to drift), or do you refactor the time logic so it relies on the actually elapsed time (slightly more effort, but robust under UI load)? This article compares options, shows the main trade-off (correctness vs. simplicity) and leads to a first step that can be retrofitted even into mature VCL/FMX applications.
Timer-Drift vermeiden: Where timer drift really comes from: UI timers are not clock generators
When a VCL-TTimer is set to 1000 ms, that does not mean: „the code runs every second.“ It is more like: „when the UI thread has time, an event will be processed in the message pump roughly on a per-second cadence.“ In the VCL this is explicitly part of the model: TTimer is tied to message processing and therefore not intended for precise timing; under load events are triggered late.[Quelle] The conclusion is stark but liberating: the timer is not „too inaccurate“ — you must not mistake it for a clock.
In FMX the implementation differs by platform, but in practice you end up in the same pattern: the Main Thread is the bottleneck for rendering, input and the event loop. If you block it or overload it with Synchronize/Queue, everything processed there shifts — including timer callbacks. This becomes particularly visible with stuttering UI animations or uneven timer calls as soon as many Synchronize blocks accumulate; the core is not mysticism but main-thread overload.[Quelle]
Decision point: What does „every X seconds“ actually mean from a business perspective?
Before you swap technology, clarify the requirement. In business software the phrase „every X seconds“ often hides very different expectations:
- Minimum interval: Something must not occur more frequently than every X seconds (e.g. retry backoff, polling).
- Drift-free rate: On average it should be correct (e.g. „3600 samples per hour“ or a runtime display that does not run away).
- Visual refresh: The UI should update regularly, but precision is secondary (progress, animations, displays).
- Wall-clock time: Something should occur at a clock-time point (e.g. 02:00), independent of runtime drift — here the system time applies, not a monotonic clock.
The most important conflict of goals arises when you expect a drift-free rate but only use a UI timer as a trigger. In that case, interval counting is almost always wrong. For minimum spacing, however, a simple timestamp-based check often suffices: „has X really elapsed since the last time?“
Options in comparison: Three approaches to handling timer drift
Realistically you encounter three approaches. They are not inherently „good“ or „bad“, but fit different goals.
| Option | Principle | Strengths | Typical weakness | Suited for |
|---|---|---|---|---|
| Interval counting | OnTimer => time += Interval | Minimal effort, quickly makes something visible | Drift is introduced as soon as callbacks are delayed | Short-lived UI effects with no functional relevance |
| Timestamp-based in the UI timer | OnTimer => Δt = now – last | Drift-free in the sense of representing real time, robust under load | You must actively decide between catch-up vs. clamp | Timeouts, backoff, status, progress, plausibility in the log |
| Scheduler/worker outside the UI | Logic ticks in the background, UI only renders | UI load has little effect on the time logic | Threading, shutdown, synchronization become mandatory | Sampling, device communication, heavier periodic tasks |
If you see drifting time today, option 2 is usually the best first step: you can keep the UI timer but correct the time logic. Option 3 is worthwhile when periodicity is functionally strict or real work happens on each tick.
The most common logic error: „Every OnTimer is a tick“
The drift often does not come „from the operating system“ but from your modeling: you treat a delayed event as if it were on time. That produces two consequences:
- Gradual time shift: your „internal time“ lags behind or runs ahead of real runtime, depending on the pattern.
- Batching effects: when the UI thread becomes free again, timer events arrive in quick succession — and your code fires actions in bursts (e.g. multiple polls, multiple DB writes).
VCL-TTimer is a textbook example: it is tied to the GUI thread’s message pump; if that is busy, timer messages are processed later.[Quelle] The architectural consequence: the timer event is a „checkpoint“, not a timebase.
Clean approach: monotonic timestamps and Δt-based time logic
The robust refactor consists of two decisions you should keep clearly separate: (1) time source, (2) update strategy.
Time source: runtime needs monotonicity, not wall time
For runtimes and time differences you want a monotonic time source — an clock that does not jump backwards and is not affected by time synchronization or manual changes. Microsoft documents high-resolution timestamp APIs and classifies them by use case; QueryPerformanceCounter (QPC) is the typical choice for high-resolution measurements.[Quelle] Practical implication: For Δt, QPC (or an Delphi-abstraction such as TStopwatch) is often more appropriate than Now. For coarser needs, GetTickCount64 is often sufficient.
The limitation of this source is important: it does not make your timer „punctual.“ It ensures that you measure delays correctly and handle them professionally.
Update strategy: measure Δt, don’t „trust the interval“
The change is conceptually small but effective: on every callback you read „now“, compute Δt since „last“ and update your state based on this actual time difference. That keeps timeouts, progress and rates plausible under load, even if the event itself arrives irregularly.
The trade-off: Catch-up vs. Clamp (and why this is a technical decision)
With Δt the next question follows automatically: what do you do when Δt is large because the UI hung? Two strategies are common; both have legitimate use cases.
Catch-up: work through missed steps
You split Δt into multiple „fixed steps“ and execute the logic in a loop until the backlog is caught up. This is attractive for fixed rates (simulation, sampling). The drawback: in the UI thread catch-up can trigger a load avalanche. A single hang then leads to many iterations that in turn block the UI thread — the next hang is inevitable.
Clamp: limit Δt, prioritize reactivity
You clamp Δt to a maximum (typically 100–200 ms for UI-near logic) and accept that you do not fully re-simulate „lost time.“ For many business processes this is even desirable: users do not want retroactive „catch-up“, but stable usability, plausible displays and timeouts that do not grow uncontrollably.
If you take sampling/control seriously, you usually end up with a combination: time logic and catch-up in a worker, UI only as a display with throttled updates.
Constructed example: drift arises from „correct-appearing“ code
Realistically account for UI load: VCL/FMX behave similarly, only the symptoms vary
In VCL and FMX the main thread is the bottleneck: input, layout, rendering, the message/event loop, and often timer callbacks run there serially. This is why the problem often gets worse when you add „a bit more logic“ in the timer: you increase work exactly where your timer is already competing for resources.
In VCL the behavior of TTimer is tied to the message pump and therefore delayed under load.[Quelle] In FMX an amplifier is often that UI-heavy Synchronize calls or a high frequency of UI updates can disrupt rendering; the described stutter effects are typical when too much work lands on the main thread.[Quelle]
Practical consequence for technical leads and admins (and for anyone who later has to explain operations): if an application executes time-critical logic on the UI thread, „under load“ is not an edge case but normal operation. Timer drift then is not a surprise, but expected system behavior.
The first step that almost always pays off: eliminate interval counting
You don’t have to pull in a complete scheduling architecture immediately. The fastest, low-risk step: wherever timing is functionally relevant, replace „tick counts“ with „time is measured.“
- Choose the time source: For runtime measurements select a monotonic source (QPC/
TStopwatchorGetTickCount64). - Store the last timestamp: Maintain a lastTimestamp per logic area (in the Controller/Service, not as a UI component detail).
- Calculate Δt: On each trigger compute Δt = now − lastTimestamp, then set lastTimestamp = now.
- Check thresholds instead of acting per tick: Tie actions to an „accumulated Δt ≥ threshold“ (e.g. 10 s), not to the number of callbacks.
- Choose clamp/catch-up consciously: Near-UI typically clamp, domain periodicity rather catch-up (in that case better run it in a worker).
- Log metrics: Record Δt min/max, handler duration and „skipped“ steps to be able to explain behavior later.
The trick with the ‚Δt sum‘ (accumulator) prevents small irregularities from immediately shifting the periodicity. You accumulate Δt and execute the action once enough time has been ’saved up‘. This turns an irregular trigger into a drift-resistant rate — without pretending UI callbacks are punctual.
Pitfalls: How drift returns despite a timestamp-based approach
System clock as runtime basis
Now is meant for wall-clock time (logs, appointments, human time). Using it for elapsed time is risky because the system clock can jump. The clean approach is: monotonic time for Δt, plus UTC/wall-clock time for audit/display, but keep them separated in logic and in the data model.
Catch-up in the UI thread
If you do catch-up in the UI timer you create a vicious cycle: a stall creates backlog, backlog creates more work on the UI, more work causes the next stall. If catch-up is necessary, that signals decoupling: a worker computes, the UI renders.
I/O or DB in the timer handler
A timer handler that performs synchronous HTTP, large DB transactions or file scans is effectively a guaranteed UI blockade. Even with perfect Δt logic, users will observe batched updates. A better structure: the timer triggers, a worker does the work, the UI receives concise updates.
Debugging distorts timing
Breakpoints in the main thread are a timing disaster. For drift analysis use lightweight measurements: measure handler duration, aggregate Δt (e.g. min/max), and log only on outliers. That gives you a picture without „slowing the app down to measure the slowdown.“
Debugging checklist: make drift visible instead of guessing
- Record Δt per tick: Not just averages, but min/max and outliers.
- Measure handler duration: How long does the timer callback itself block?
- Count UI update frequency: How many Synchronize/Queue/Invalidate operations per second are triggered?
- Define a ‚budget‘: e.g. „Timer-Handler < 2 ms“ as a target; above that it’s a performance issue, not a timer issue.
- Produce load reproducibly: Large datasets in the grid, intentional repaint, simulated I/O latency (without breakpoints).
That lets you distinguish cleanly: is the timer late because the UI pipeline is blocked? Or is your handler blocking? Or both? Only then is it worthwhile to change threads, adopt timer alternatives or optimize rendering.
When is it really worth moving the timer out of the UI?
A timestamp-based UI timer already solves many problems. A larger refactor (worker/scheduler) is justified when one of these points applies:
- Strict periodicity: a rate must be met for functional reasons (sampling, device communication, control).
- Work per tick is non-trivial: I/O, DB, parsing, cryptography, larger computations.
- Operation-critical UIs: terminals, POS, control rooms — the UI must remain responsive under load.
- Reproducibility: timing must be testable and supportable (monitoring, log correlation).
The clean target architecture is usually: a background core with a monotonic time base and its own load control; the UI is rate-limited for updates (e.g. 5–10 updates/s suffice for many displays) and thus remains stable. That not only reduces drift, it reduces support discussions: „Why was the timeout suddenly 3 minutes?“ can then be answered with metrics.
Quellen richtig lesen: Was sie absichern – und welche Lücke du selbst schließen musst
The Embarcadero documentation for Vcl.ExtCtrls.TTimer provides the central basis: the timer is attached to the GUI message processing and is therefore not precise under load.[Quelle] The documentation, however, does not give you a ready-made strategy for catch-up/clamp or decoupling. That is architectural work derived from your functional requirements.
Microsoft’s classification of high-resolution time stamps explains why you should treat time as a measured quantity: APIs like QueryPerformanceCounter are intended to compute reliable time differences; you measure time instead of relying on event regularity.[Quelle] The gap remains: you still need a trigger (timer, wait, loop). That is exactly why the combination makes sense: the timer as an alarm, monotonic timestamps as the source of truth.
The final picture: What improves immediately after the change
After the refactor the result is rarely “microsecond precision.” The gain is predictability. Timeouts no longer silently run longer, backoff behaves consistently, progress and countdowns remain plausible, and logs again provide an explainable timeline. Above all, you gain a new diagnostic tool: once Δt and handler duration are recorded, you locate the real causes (repaint storms, too many Synchronize calls, I/O in the UI) much faster.
If you want to start today: search the code for places that derive time from the number of timer events („+Interval“, counters per tick, countdown per tick). Convert that logic to monotonic timestamps and Δt. After that you can decide precisely which parts belong in a worker and which may deliberately remain UI-near.
Sources and further information
The technical core statements were editorially contextualized based on the following external sources.
- Vcl.ExtCtrls.TTimer – RAD Studio API Documentation (docwiki.embarcadero.com)
VCL TTimer is bound to message processing in the GUI thread and is therefore not a precision timer; under load events are triggered late. - Acquiring high-resolution time stamps – Win32 apps | Microsoft Learn (learn.microsoft.com)
For precise time differences under Windows monotonic, high-resolution time stamps such as QueryPerformanceCounter are intended; the choice of timestamp API depends on the precision required. - Why can a `TSkAnimatedImage` stutter when FMX work is wrapped in `TThread.Synchronize`? – Stack Overflow for Agents (agents.stackoverflow.com)
In FMX additional Main-Thread work (e.g. via Synchronize) can cause stuttering/delays because the UI pipeline is processed on the Main Thread. - performance – Why is a Timer on Android more accurate when a finger is touching the screen? – Stack Overflow (stackoverflow.com)
Timer accuracy in an Android/FMX context can be affected by event-loop activity; timers are essentially tied to main-thread processing.
For this topic, Delphi Ttimer and Fmx timer drift are also important. The article clearly contextualizes these aspects and shows what matters in everyday operation.
Discuss a project or modernization initiative with Net-Base.
Next step
When the topic becomes an actual project, architecture, existing systems and operations should be considered together from the outset.
We support not only with individual issues, but also when source snippets, legacy topics, or portal ideas are to be turned into a robust enterprise project.
- Current state, target state and technical risks are assessed jointly.
- REST, data access, portals and rollout are not deferred to a later stage as secondary consequences.
- You can see early on which path is economically and operationally viable.