Command Palette

Search for a command to run...

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

axiom-timer-patterns-ref

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

Timer, DispatchSourceTimer, Combine Timer.publish, AsyncTimerSequence, Task.sleep API reference with lifecycle diagrams, RunLoop modes, and platform…

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

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

Timer Patterns Reference

Complete API reference for iOS timer mechanisms. For decision trees and crash prevention, see axiom-timer-patterns.


Part 1: Timer API

Timer.scheduledTimer (Block-Based)

// Most common — block-based, auto-added to current RunLoop
let timer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { [weak self] _ in
    self?.updateProgress()
}

Key detail: Added to .default RunLoop mode. Stops during scrolling. See Part 1 RunLoop modes table below.

Timer.scheduledTimer (Selector-Based)

// Objective-C style — RETAINS TARGET (leak risk)
let timer = Timer.scheduledTimer(
    timeInterval: 1.0,
    target: self,       // Timer retains self!
    selector: #selector(update),
    userInfo: nil,
    repeats: true
)

Danger: This API retains target. If self also holds the timer, you have a retain cycle. The block-based API with [weak self] is always safer.

Timer.init (Manual RunLoop Addition)

// Create timer without adding to RunLoop
let timer = Timer(timeInterval: 1.0, repeats: true) { [weak self] _ in
    self?.updateProgress()
}

// Add to specific RunLoop mode
RunLoop.current.add(timer, forMode: .common)  // Survives scrolling

timer.tolerance

timer.tolerance = 0.1  // Allow 100ms flexibility for system coalescing

System batches timers with similar fire dates when tolerance is set. Minimum recommended: 10% of interval. Reduces CPU wakes and energy consumption.

RunLoop Modes

Mode Constant When Active Timer Fires?
Default .default / RunLoop.Mode.default Normal user interaction Yes
Tracking .tracking / RunLoop.Mode.tracking Scroll/drag gesture active Only if added to .common
Common .common / RunLoop.Mode.common Pseudo-mode (default + tracking) Yes (always)

timer.invalidate()

timer.invalidate()  // Stops timer, removes from RunLoop
// Timer is NOT reusable after invalidate — create a new one
timer = nil          // Release reference

Key detail: invalidate() must be called from the same thread that created the timer (usually main thread).

timer.isValid

if timer.isValid {
    // Timer is still active
}

Returns false after invalidate() or after a non-repeating timer fires.

Timer.publish (Combine)

Timer.publish(every: 1.0, tolerance: 0.1, on: .main, in: .common)
    .autoconnect()
    .sink { [weak self] _ in
        self?.updateProgress()
    }
    .store(in: &cancellables)

See Part 3 for full Combine timer details.


Part 2: DispatchSourceTimer API

Creation

// Create timer source on a specific queue
let queue = DispatchQueue(label: "com.app.timer")
let timer = DispatchSource.makeTimerSource(flags: [], queue: queue)

flags: Usually empty ([]). Use .strict for precise timing (disables system coalescing, higher energy cost).

Schedule

// Relative deadline (monotonic clock)
timer.schedule(
    deadline: .now() + 1.0,     // First fire
    repeating: .seconds(1),     // Interval
    leeway: .milliseconds(100)  // Tolerance (like Timer.tolerance)
)

// Wall clock deadline (survives device sleep)
timer.schedule(
    wallDeadline: .now() + 1.0,
    repeating: .seconds(1),
    leeway: .milliseconds(100)
)

deadline vs wallDeadline: deadline uses monotonic clock (pauses when device sleeps). wallDeadline uses wall clock (continues across sleep). Use deadline for most cases.

Event Handler

timer.setEventHandler { [weak self] in
    self?.performWork()
}

Before cancel: Set handler to nil to break retain cycles:

timer.setEventHandler(handler: nil)
timer.cancel()

Lifecycle Methods

timer.activate()   // Start — can only call ONCE (idle → running)
timer.suspend()    // Pause (running → suspended)
timer.resume()     // Unpause (suspended → running)
timer.cancel()     // Stop permanently (must NOT be suspended)

State Machine Lifecycle

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

Critical rules:

  • activate() can only be called once (idle → running)
  • cancel() requires non-suspended state (resume first if suspended)
  • cancelled is terminal — no further operations allowed
  • Dealloc requires non-suspended state (cancel first if needed)

Leeway (Tolerance)

// Leeway values
timer.schedule(deadline: .now(), repeating: 1.0, leeway: .milliseconds(100))
timer.schedule(deadline: .now(), repeating: 1.0, leeway: .seconds(1))
timer.schedule(d
Полный SKILL.md на GitHub

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

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

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

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

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

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

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

FAQ

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

Timer, DispatchSourceTimer, Combine Timer.publish, AsyncTimerSequence, Task.sleep API reference with lifecycle diagrams, RunLoop modes, and platform availability

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

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

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

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

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

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