AI-powered crash analysis is now available on all plans — including Free.Read the crash analysis guide

Debug Timer & Alarm Crashes: NSTimer & AlarmManager

NFNourin Mahfuj Finick··10 min read

Timers and alarms are the silent workhorses of every mobile app — they drive autosave, polling, countdowns, debouncing, animation ticks, and scheduled notifications. They are also responsible for some of the most maddening crashes in production: an NSTimer retain cycle that fires into a deallocated view controller, an AlarmManager alarm that never goes off after the device enters Doze, a PendingIntent that throws a NullPointerException because it was created mutable. Unlike a null-pointer on the main path, a timer crash rarely reproduces in the debugger, because it depends on timing, threading, and power state. In this guide we break down the most common timer and alarm crash vectors across iOS, Android, Flutter, and coroutines — with concrete Swift and Kotlin fixes for each.

The unifying theme is simple: timers are sources of deferred callbacks, and almost every crash around them comes from one of four mistakes — a strong reference cycle that keeps a timer or its target alive past its lifetime, a timer on a thread that never pumps its run loop, a cancellation that races a resume or a fire, or a platform power policy that silently suppresses delivery. Fix those four and you eliminate most timer-related crashes.

Why timer and alarm crashes slip past testing

Scheduled-work bugs are hard to catch for three reasons. They are time-dependent — a Timer firing after deallocation only crashes once the interval elapses, seconds or minutes after the bug that caused it. They are thread-dependent — a timer scheduled on a background thread without a run loop will never fire, which looks like a hang, not a crash, until the state it was supposed to update goes stale. And they are power-state-dependent — Android's Doze and App Standby can defer or drop AlarmManager alarms entirely, so a feature that works on a plugged-in test device fails on a real user's phone in their pocket. Apple's Timer documentation notes that a timer needs a run loop to deliver its fires, and Android's Doze and App Standby guide documents how aggressively the OS defers alarms.

The practical consequence: the crash happens far from the code that caused it, so the context around the schedule matters as much as the stack at the crash — exactly the situation structured crash reporting and session replay are built for.

iOS: NSTimer and Timer crash debugging

The NSTimer retain cycle and firing after dealloc

The classic iOS timer crash is the target-action retain cycle. Timer.scheduledTimer(withTimeInterval:target:selector:userInfo:repeats:) (and its older NSTimer counterpart) retains its target, so if the target is the same object that owns the timer, the two pin each other in memory forever. When some other path eventually frees the target, the next fire delivers a selector to a dangling pointer — EXC_BAD_ACCESS, or the classic "timer fired after dealloc" crash. The block-based API removes the target retention but reintroduces it the moment you capture self strongly inside the block.

// WRONG: the timer retains self, and self retains the timer.
timer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { _ in
    self.refresh() // strong capture -> retain cycle
}

The fix is to capture self weakly and invalidate the timer in deinit or viewDidDisappear. For a broader treatment of retain cycles beyond timers, see our guide on mobile memory leak debugging.

timer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { [weak self] _ in
    self?.refresh()
}
deinit { timer?.invalidate() }

Timers scheduled on a thread with no run loop

A timer only fires if the thread it is scheduled on pumps a run loop. Timer.scheduledTimer adds the timer to the current run loop, so calling it from a GCD background queue attaches it to a thread with no running RunLoop — it never fires, and you get a silent hang instead of a crash. The fix is to schedule on the main thread, or create the timer and add it to a RunLoop you control:

let timer = Timer(timeInterval: 1.0, repeats: true) { _ in
    // work
}
RunLoop.main.add(timer, forMode: .common)

Apple's RunLoop documentation describes the modes a timer can use — .common avoids the trap where a timer added to .default stops firing during scroll or tracking gestures, which presents as "my timer pauses while the user drags the list."

DispatchSourceTimer cancellation races

DispatchSourceTimer is the preferred one-shot and repeating timer on dispatch queues, but it has sharp edges. A cancelled source must not be resumed, and a source resumed twice traps at runtime with EXC_BAD_INSTRUCTION. The standard crash is a cancellation flag checked on one queue while the event handler resumes the source on another, racing each other. The DispatchSourceTimer reference documents the cancel-then-resume contract; the safe pattern is a single serial owner that guards every resume behind the cancelled state.

let source = DispatchSource.makeTimerSource(queue: queue)
source.setEventHandler { /* work */ }
source.schedule(deadline: .now() + 1.0, repeating: 1.0)
source.resume()
// Single owner, single cancellation path:
source.setCancelHandler { source.cancel() }

CADisplayLink retain cycles

CADisplayLink is a display-linked timer that fires every frame — and it retains its target exactly like NSTimer does. A CADisplayLink stored in a view controller that is also its target forms the same retain cycle, leaking the controller and, if the link keeps firing after teardown, delivering callbacks into a dead object. Use a weak proxy or the block-based add(to:forMode:) with a weak capture, and invalidate when the view disappears. Our animation and transition crash debugging guide covers CADisplayLink alongside the other animation tick sources.

Android: AlarmManager and Handler crash debugging

AlarmManager exact vs inexact alarms

AlarmManager is the OS-level scheduler for firing work at a wall-clock or elapsed-realtime moment. The single most common failure is a mis-set alarm: setExactAndAllowWhileIdle, set, and setWindow behave very differently under battery optimization, and code that assumes exact delivery fires late or not at all on a Doze-affected device. Exact alarms are also restricted on newer Android — apps need SCHEDULE_EXACT_ALARM or the user-granted USE_EXACT_ALARM path, and without it setExact silently falls back. Choose the least-strict API that satisfies the requirement, and prefer inexact, windowed delivery for non-critical work.

Doze and App Standby suppressing alarms

When a device enters Doze, the system defers standard alarms, network access, and wake locks until a maintenance window. An app that schedules a heartbeat, sync, or reminder with a plain set() sees those alarms batched or delayed for minutes to hours, and the feature simply stops working on real devices. The Doze and App Standby guide explains the maintenance-window model and the setAndAllowWhileIdle escape hatch. The rule: use setAndAllowWhileIdle (or a WorkManager job) only for work that truly must run, and design everything else to tolerate deferral. For the OS-managed side of this, see our background task scheduling debugging guide, which covers WorkManager and BGTaskScheduler.

PendingIntent crashes and FLAG_IMMUTABLE

The most frequently seen AlarmManager crash is not in the alarm at all — it is in the PendingIntent. Starting with Android 12, every PendingIntent must declare mutability via FLAG_IMMUTABLE or FLAG_MUTABLE, and creating one without either throws IllegalArgumentException. Separately, passing a mutable PendingIntent into AlarmManager.set can throw a NullPointerException on some OEM builds, because the system tries to fill in the intent's extras. The PendingIntent reference documents the mutability flags. Always build immutable intents for alarms:

val intent = Intent(this, AlarmReceiver::class.java)
val pending = PendingIntent.getBroadcast(
    this, 0, intent,
    PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT
)
alarmManager.setAndAllowWhileIdle(
    AlarmManager.ELAPSED_REALTIME_WAKEUP,
    SystemClock.elapsedRealtime() + interval,
    pending
)

Handler.postDelayed and Activity leaks

Handler.postDelayed is Android's in-process timer, and it leaks the way NSTimer does: a Handler is tied to its thread's looper, and an anonymous Runnable that captures an Activity keeps that activity alive until the runnable runs or is removed. After a rotation, the delayed runnable holds a stale reference — and when it fires, it mutates a destroyed view, the source of a large share of "crash on rotation" reports. Always removeCallbacksAndMessages(null) in onDestroy, use a lifecycle-aware viewLifecycleOwner, and prefer coroutines with structured concurrency so cancellation is automatic.

CountDownTimer, ScheduledExecutorService, and java.util.Timer

Three more in-process schedulers each carry a specific leak. CountDownTimer is easy to forget to cancel — an abandoned countdown keeps ticking on the main thread and fires onFinish into a dead view. java.util.Timer and TimerTask create a dedicated non-daemon thread that keeps the process alive and accumulates tasks if you never call cancel(). ScheduledExecutorService is the best of the three, but its pool threads linger unless you call shutdown(). Treat every one with the same discipline: store the handle, cancel it in the lifecycle callback that mirrors where you started it, and verify with a leak detector rather than assuming.

Cross-platform timer crashes

Flutter's Timer and Timer.periodic mirror the Dart async model: they fire on the isolate's event loop and, like NSTimer, leak work if a widget is disposed while a periodic timer is still running. The canonical Flutter crash is a Timer.periodic started in initState that calls setState after the widget is unmounted — the framework throws because you are mutating a disposed element. Store the Timer and call cancel() in dispose(), and never start periodic work in build(). Dart timers are also paused by the isolate scheduler, so long timers do not fire while the app is backgrounded — a close cousin of Doze.

On the reactive side, RxJava schedulers and Kotlin coroutines' delay() are structured alternatives that sidestep most manual-leak problems: a coroutine cancelled through its scope cannot fire its callback into a dead object. For the coroutine angle specifically, our Kotlin coroutines crash debugging guide covers cancellation and scope leaks in detail. The cross-platform lesson is uniform: prefer a scheduler with structured cancellation, and when you must use a raw timer, pair every schedule with a matching cancel in the teardown path.

A repeatable timer-debugging workflow

When a timer or alarm bug lands on your desk, work through four questions in order. First, is the schedule paired with a cancel? Grep for every scheduledTimer, postDelayed, set, and periodic, and confirm each has a matching invalidate/remove/cancel in the lifecycle mirror. Second, which thread owns the timer, and does it pump its loop? An iOS timer on a GCD queue without a RunLoop, or an Android handler bound to a dead looper, is the root cause of most "never fires" reports. Third, is the target retained or captured strongly? Weak captures and FLAG_IMMUTABLE fix the dangling-pointer and mutability crashes. Fourth, is delivery subject to a power policy? If the feature only fails on real devices in the field, Doze, App Standby, or the iOS background-execution window is the likely culprit.

Because these bugs are timing- and state-dependent, a crash report that only contains the final stack is usually not enough — you need the schedule site, the thread, and the power state at delivery time. Bugspulse captures the full exception alongside session and device context, so a "timer fired after dealloc" or a missing-alarm report shows you which timer and which thread, not just a dangling pointer. Correlating the crash with the exact scheduling call turns a week of guessing into a one-line fix.

Debug timer and alarm crashes with confidence

NSTimer retain cycles, silent run-loop misses, DispatchSourceTimer resume races, Doze suppression, and PendingIntent mutability errors all share one shape: a deferred callback delivered to the wrong object, on the wrong thread, at the wrong time. Every one has a mechanical fix — weak captures and explicit invalidation on iOS, FLAG_IMMUTABLE and lifecycle-aware cancellation on Android, structured concurrency and dispose()-time cancel() in Flutter and coroutines. Pair every schedule with a cancel, keep timers on a thread that pumps its loop, and design for power policy instead of fighting it, and the vast majority of timer and alarm crashes disappear.

Ready to stop chasing timer crashes across fragmented devices and power states? Create a Bugspulse account and see every scheduled-work failure — its timer, its thread, and its trigger — in one place.