Command Palette

Search for a command to run...

UnylyUnyly
Назад к скиллам

axiom-timer-patterns

БесплатноБез исполняемых скриптовНе проверен

Use when implementing timers, debugging timer crashes (EXC_BAD_INSTRUCTION), Timer stops during scrolling, or choosing between…

ComeOnOliverот ComeOnOliver★ 67 звёзд на GitHub

Об этом скилле

Timer Safety Patterns

Overview

Timer-related crashes are among the hardest to diagnose because they're often intermittent and the crash log points to GCD internals, not your code. Core principle: DispatchSourceTimer has a state machine — violating it causes deterministic EXC_BAD_INSTRUCTION crashes that look random. Timer (NSTimer) has a RunLoop mode trap that silently stops your timer during scrolling. Both are preventable with the patterns in this skill.

Example Prompts

  • "My timer stops when the user scrolls"
  • "EXC_BAD_INSTRUCTION crash in my timer code"
  • "Should I use Timer or DispatchSourceTimer?"
  • "How do I safely cancel a DispatchSourceTimer?"
  • "My DispatchSourceTimer crashes on dealloc"
  • "Timer keeps running after I dismiss the view controller"

Part 1: Timer vs DispatchSourceTimer Decision Tree

Feature Timer DispatchSourceTimer AsyncTimerSequence
Thread safety Main thread only (RunLoop-bound) Any queue (you choose) Task-bound (structured concurrency)
Scrolling survival Only in .common mode Always (no RunLoop dependency) Always (no RunLoop dependency)
Precision Low (RunLoop coalescing) High (GCD scheduling) Medium (clock-dependent)
Lifecycle complexity Low (invalidate + nil) High (state machine, 4 crash patterns) Low (task cancellation)
iOS version 2.0+ 8.0+ (GCD) 16.0+
Use case UI updates on main thread Background work, precise timing, custom queues Modern async code, structured concurrency

Quick Decision

Need a simple UI update timer?
├─ Yes → Timer (with .common RunLoop mode)
│
Need precise timing or background queue?
├─ Yes → DispatchSourceTimer (with SafeDispatchTimer wrapper)
│
Writing modern async/await code on iOS 16+?
├─ Yes → AsyncTimerSequence (ContinuousClock.timer)
│
Need Combine integration?
└─ Yes → Timer.publish

Part 2: RunLoop Mode Gotcha

Timer stops firing during scrolling. This is the single most common timer bug in iOS development.

Why It Happens

Timer.scheduledTimer adds the timer to the current RunLoop in .default mode. When the user scrolls (UIScrollView, SwiftUI ScrollView, List), the RunLoop switches to .tracking mode. The timer doesn't fire in .tracking mode because it was only registered for .default.

Time cost: Timer mysteriously stops during scroll → 30+ min debugging if you don't know about RunLoop modes.

❌ Broken — Timer stops during scrolling

// BAD: Timer added to .default mode (implicit)
let timer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { [weak self] _ in
    self?.updateProgress()
}
// Timer STOPS when user scrolls any UIScrollView or SwiftUI List

✅ Fixed — Timer survives scrolling

// GOOD: Explicitly add to .common mode (includes both .default and .tracking)
let timer = Timer(timeInterval: 1.0, repeats: true) { [weak self] _ in
    self?.updateProgress()
}
RunLoop.current.add(timer, forMode: .common)

✅ Fixed — Combine Timer survives scrolling

// GOOD: Timer.publish with .common mode — survives scrolling in SwiftUI
Timer.publish(every: 1.0, tolerance: 0.1, on: .main, in: .common)
    .autoconnect()
    .sink { [weak self] _ in
        self?.updateProgress()
    }
    .store(in: &cancellables)

Key: The in: parameter defaults to .default if omitted — always specify .common explicitly.

RunLoop Modes

Mode When Active Timer Fires?
.default Normal interaction Yes
.tracking During scrolling Only if added to .common
.common Pseudo-mode: includes .default + .tracking Yes (always)

Part 3: The 4 DispatchSourceTimer Crash Patterns

Each of these causes EXC_BAD_INSTRUCTION — a crash that points to GCD internals, making it hard to trace back to your timer code.

Crash Frame → Pattern Mapping

When you see EXC_BAD_INSTRUCTION in a crash log, match the top frame:

Top Crash Frame Crash Pattern Fix
dispatch_source_cancel Crash 2: Cancel while suspended resume() before cancel()
_dispatch_source_dispose Crash 3: Dealloc while suspended Resume + cancel before releasing
dispatch_resume Crash 4: Resume after cancel Check isCancelled before operating
_dispatch_source_refs_t / suspend count Crash 1: Unbalanced suspend Track state, only suspend if running

DispatchSourceTimer State Machine

                    activate()
        idle ──────────────► running
                               │  ▲
                    suspend()  │  │  resume()
                               ▼  │
                            suspended
                               │
                    resume() + cancel()
                               │
                               ▼
                           cancelled (terminal)

CRASH ZONES:
  suspende
Полный SKILL.md на GitHub

Установить axiom-timer-patterns в Claude Code и Claude Desktop

Зарегайся, чтобы установить скилл

Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.

  • Открой команду установки в одну строку
  • Сохраняй скиллы в синхронизируемую библиотеку
  • Уведомления, когда скиллы обновляются
Зарегаться бесплатноУ меня уже есть аккаунт

Разрешённые инструменты

Инструменты, которые скиллу разрешено вызывать.

Без ограничений — скилл может использовать любой инструмент.

FAQ

Что делает скилл axiom-timer-patterns?

Use when implementing timers, debugging timer crashes (EXC_BAD_INSTRUCTION), Timer stops during scrolling, or choosing between Timer/DispatchSourceTimer/Combine/async timer APIs

Как установить скилл axiom-timer-patterns?

Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.

Скилл axiom-timer-patterns запускает скрипты?

Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.

Похожие скиллы

Сравнить axiom-timer-patterns с