Token导航 LogoToken导航

Agent Skill · 开发

axiom-timer-patterns(公理定时器模式)

axiom-timer-patterns 用于处理 GitHub 仓库、Issue、Pull Request 和代码协作信息,适合在 Codex、Claude、Cursor、Gemini CLI 中需要围绕仓库状态、代码变更或协作事项进行整理时使用。可结合来源仓库、安装命令和原始 README 继续核验具体用法。安装前建议确认权限范围、维护状态,以及是否会触发联网、命令执行或文件读写。

axiom-timer-patterns 是开发类 Agent Skill,可用宿主为 Codex、Claude、Cursor、Gemini CLI,通过GitHub 仓库获取,权限为执行命令;许可证信息还不明确,第三方扫描已通过,按安装量在开发类的 21,746 个 Skill 里排第 11,015。

总安装 1,976周安装 84GitHub Stars 868下载 692核验 2026-05-01

安装说明

本站只整理中文说明,不托管安装包,也不代用户安装。
GitHub
许可证
unknown

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:axiom-timer-patterns(公理定时器模式)
来源仓库:https://github.com/charleswiltgen/axiom
仓库路径:skills/axiom-timer-patterns
安装命令:
npx skills add https://github.com/charleswiltgen/axiom --skill axiom-timer-patterns
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。该命令会通过 npx skills 从第三方来源获取 Skill;本站只展示命令,不托管安装包,也不自动执行。

skills.shnpx skills
npx skills add https://github.com/charleswiltgen/axiom --skill axiom-timer-patterns

这个 Skill 是做什么的

开发类 Skill 面向写代码、改代码和排查问题,一般会读写仓库文件,部分还会执行构建或测试命令。

axiom-timer-patterns 揭示 Timer 与 DispatchSourceTimer 的常见陷阱与安全使用模式。适用于解决定时器在滚动时静默停止或 EXC_BAD_INSTRUCTION 崩溃等疑难问题。强调 RunLoop 模式选择(如 .common)对持续运行的关键影响,避免模态切换导致中断。

所有定时器操作必须遵循状态机规则,否则将引发确定性崩溃难以追踪。推荐优先使用 Swift Concurrency 的 Task.sleep() 替代传统定时器以提升可维护性。

来源仓库内路径:skills/axiom-timer-patterns

上手步骤

4 步
  1. 1

    确认自己的宿主工具

    公开资料标注支持 Codex、Claude、Cursor、Gemini CLI;先确认自己用的是其中之一,再按对应工具的 Skills 目录放置。

  2. 2

    拿到安装命令

    可以直接复制的命令是 npx skills add https://github.com/charleswiltgen/axiom --skill axiom-timer-patte…;命令里的占位符换成自己的路径或密钥再执行。

  3. 3

    安装后重启宿主

    命令执行完要完全退出宿主工具再打开,让新装的 Skill 被重新扫描到,否则列表里可能看不到。

  4. 4

    按最小权限试用

    它需要执行命令,先在测试目录或测试账号里跑,确认没问题再放到正式项目。

常见问题

6 条

axiom-timer-patterns 怎么安装?

在终端执行 npx skills add https://github.com/charleswiltgen/axiom --skill axiom-timer-patterns。装完完全退出宿主工具再打开,让它重新扫描本地 Skill。

axiom-timer-patterns 支持哪些 AI 工具?

公开资料标注支持 Codex、Claude、Cursor、Gemini CLI。其他工具只要能读取本地 Skill 目录,一般也能手动放进去,但要自己确认触发方式是否一致。

axiom-timer-patterns 需要什么权限?

权限级别是执行命令。安装流程涉及命令执行,可能通过 npx skills add https://github.com/charleswiltgen/axiom --skill axiom-timer-patterns 联网下载 Skill 或依赖。用户安装前应确认命令来源、仓库内容和执行环境。

axiom-timer-patterns 是免费的吗?

公开资料没有标注明确许可证,收费和商用限制都无法确认。正式使用前请到来源仓库核对授权说明。

axiom-timer-patterns 用的人多吗?

公开数据是累计安装 1,976 次,近一周安装 84 次,下载 692 次,GitHub 868 星。这些数字来自第三方目录统计,只能当作热度参考,不代表质量或安全性。

axiom-timer-patterns 安全吗?

第三方扫描结果为通过,但这只覆盖已知的静态检查项,不能替代自己读一遍源码和安装命令。

值得选的地方和要先想清楚的地方

值得选的地方

  • 同时适配 4 种工具,换客户端不用重新找替代品。
  • 第三方扫描已通过,常见的高风险行为没有命中。

先想清楚的地方

  • 需要执行命令,装到常用环境前要先评估影响面。
  • 许可证没有明确标注,能不能商用、能不能再分发都不确定。
  • 第三方目录整理,版本更新和行为细节以来源仓库为准。

适不适合你

更适合

  • 已经在用 Codex,想直接扩展它能力的人。
  • 需要处理开发类任务、又不想每次都手写提示词的人。

不太适合

  • 不能接受 Skill 在你机器上执行命令的人。
  • 需要明确授权才能用到公司项目里的场景。
  • 需要厂商级技术支持和 SLA 的生产系统。

开发类 Skill 对比

6 个同类
Skill总安装GitHub 星权限许可证扫描
skill-vetter

技能审查员 · OpenClaw

8,779,018986操作浏览器MIT-0通过
ontology

本体论 · OpenClaw

6,636,960576只读MIT-0通过
entra-app-registration

内部应用程序注册 · Codex、Claude

6,631,872764接触敏感数据未明确通过
entra-app-registration

内部应用程序注册 · Codex、Claude

3,757,680201接触敏感数据未明确通过
nano-banana-pro

纳米香蕉专业版 · OpenClaw

3,526,898364接触敏感数据MIT-0有提醒
axiom-timer-patterns

公理定时器模式 · 本页

1,976868执行命令未明确通过

按安装量取同分类前几名;数字来自第三方目录统计,只作热度参考,不代表质量结论。

SKILL.md 原文

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

FeatureTimerDispatchSourceTimerAsyncTimerSequence
Thread safetyMain thread only (RunLoop-bound)Any queue (you choose)Task-bound (structured concurrency)
Scrolling survivalOnly in .common modeAlways (no RunLoop dependency)Always (no RunLoop dependency)
PrecisionLow (RunLoop coalescing)High (GCD scheduling)Medium (clock-dependent)
Lifecycle complexityLow (invalidate + nil)High (state machine, 4 crash patterns)Low (task cancellation)
iOS version2.0+8.0+ (GCD)16.0+
Use caseUI updates on main threadBackground work, precise timing, custom queuesModern 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

ModeWhen ActiveTimer Fires?
.defaultNormal interactionYes
.trackingDuring scrollingOnly if added to .common
.commonPseudo-mode: includes .default + .trackingYes (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 FrameCrash PatternFix
dispatch_source_cancelCrash 2: Cancel while suspendedresume() before cancel()
_dispatch_source_disposeCrash 3: Dealloc while suspendedResume + cancel before releasing
dispatch_resumeCrash 4: Resume after cancelCheck isCancelled before operating
_dispatch_source_refs_t / suspend countCrash 1: Unbalanced suspendTrack state, only suspend if running

DispatchSourceTimer State Machine

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

CRASH ZONES:
  suspended → cancel()  = EXC_BAD_INSTRUCTION
  suspended → dealloc   = EXC_BAD_INSTRUCTION
  suspended → suspend() = suspend count underflow on dealloc
  cancelled → resume()  = EXC_BAD_INSTRUCTION

Crash 1: Suspend While Already Suspended

Calling suspend() multiple times without matching resume() calls. Each suspend() increments an internal counter. On dealloc, if the suspend count isn't zero, GCD crashes.

❌ Crash
let timer = DispatchSource.makeTimerSource(queue: queue)
timer.schedule(deadline: .now(), repeating: 1.0)
timer.setEventHandler { doWork() }
timer.activate()

// User triggers pause twice rapidly
timer.suspend()  // suspend count = 1
timer.suspend()  // suspend count = 2

timer.resume()   // suspend count = 1
// Timer deallocated with suspend count = 1 → EXC_BAD_INSTRUCTION
✅ Safe
// Track state — only suspend if running
var isRunning = true

func pause() {
    guard isRunning else { return }
    timer.suspend()
    isRunning = false
}

func unpause() {
    guard !isRunning else { return }
    timer.resume()
    isRunning = true
}

Crash 2: Cancel While Suspended

GCD requires a dispatch source to be in a non-suspended state before cancellation. Cancelling a suspended timer crashes immediately.

❌ Crash
let timer = DispatchSource.makeTimerSource(queue: queue)
timer.schedule(deadline: .now(), repeating: 1.0)
timer.setEventHandler { doWork() }
timer.activate()

timer.suspend()
timer.cancel()  // EXC_BAD_INSTRUCTION — can't cancel while suspended
✅ Safe
// ALWAYS resume before cancelling
timer.resume()   // Move out of suspended state
timer.cancel()   // Now safe to cancel

Crash 3: Dealloc While Suspended

Setting the timer to nil (or letting it go out of scope) while suspended. Deallocation internally attempts cleanup that fails on a suspended source.

❌ Crash
var timer: DispatchSourceTimer?

func startTimer() {
    timer = DispatchSource.makeTimerSource(queue: queue)
    timer?.schedule(deadline: .now(), repeating: 1.0)
    timer?.setEventHandler { [weak self] in self?.doWork() }
    timer?.activate()
}

func pauseTimer() {
    timer?.suspend()
}

func cleanup() {
    timer = nil  // Dealloc while suspended → EXC_BAD_INSTRUCTION
}
✅ Safe
func cleanup() {
    // Resume before releasing
    timer?.resume()
    timer?.cancel()
    timer = nil  // Now safe — timer is in cancelled state
}

Crash 4: Operate After Cancel

Calling resume() or suspend() on a cancelled timer. Cancellation is a terminal state — the timer cannot be reused.

❌ Crash
timer.cancel()
timer.resume()  // EXC_BAD_INSTRUCTION — can't resume a cancelled source
✅ Safe
// Track cancellation state
var isCancelled = false

func cancel() {
    guard !isCancelled else { return }
    timer.cancel()
    isCancelled = true
}

func resume() {
    guard !isCancelled else { return }  // Check before operating
    timer.resume()
}

Part 4: SafeDispatchTimer Wrapper

Copy-paste this class to prevent all 4 crash patterns. State machine enforces valid transitions.

final class SafeDispatchTimer {
    enum State { case idle, running, suspended, cancelled }

    private(set) var state: State = .idle
    private let timer: DispatchSourceTimer

    init(queue: DispatchQueue = DispatchQueue(label: "safe-dispatch-timer")) {
        timer = DispatchSource.makeTimerSource(queue: queue)
    }

    func schedule(interval: TimeInterval, handler: @escaping () -> Void) {
        guard state == .idle else { return }
        timer.schedule(deadline: .now() + interval, repeating: interval)
        timer.setEventHandler(handler: handler)
        timer.activate()
        state = .running
    }

    func suspend() {
        guard state == .running else { return }
        timer.suspend()
        state = .suspended
    }

    func resume() {
        guard state == .suspended else { return }
        timer.resume()
        state = .running
    }

    func cancel() {
        switch state {
        case .suspended:
            timer.resume()  // Must resume before cancel
            timer.cancel()
        case .running:
            timer.cancel()
        case .idle, .cancelled:
            return
        }
        state = .cancelled
    }

    deinit {
        cancel()  // Safe cleanup regardless of current state
    }
}

Usage

class BackgroundPoller {
    private var timer: SafeDispatchTimer?

    func start() {
        timer = SafeDispatchTimer()
        timer?.schedule(interval: 5.0) { [weak self] in
            self?.fetchData()
        }
    }

    func pause() {
        timer?.suspend()  // Safe — no-op if not running
    }

    func unpause() {
        timer?.resume()  // Safe — no-op if not suspended
    }

    func stop() {
        timer?.cancel()  // Safe — handles any state
        timer = nil
    }
}

Part 5: Thread Safety

Always Use a Dedicated Serial Queue

DispatchSourceTimer fires its event handler on the queue you specify at creation. Using a concurrent queue creates race conditions when multiple firings overlap or when you modify shared state from the handler.

❌ Race Condition
// BAD: Concurrent queue — handler can fire while previous invocation is still running
let timer = DispatchSource.makeTimerSource(queue: DispatchQueue.global())
timer.setEventHandler {
    self.count += 1          // Race condition
    self.processItem(count)  // Overlapping invocations
}
✅ Serial Queue
// GOOD: Dedicated serial queue — handler invocations are serialized
let timerQueue = DispatchQueue(label: "com.app.timer-queue")
let timer = DispatchSource.makeTimerSource(queue: timerQueue)
timer.setEventHandler { [weak self] in
    self?.count += 1          // Safe — serial queue
    self?.processItem(count)  // No overlap
}

Main Queue for UI Updates

If your timer handler updates UI, dispatch to main:

let timer = DispatchSource.makeTimerSource(queue: timerQueue)
timer.setEventHandler { [weak self] in
    let result = self?.computeResult()
    DispatchQueue.main.async {
        self?.updateUI(with: result)
    }
}

Part 6: Anti-Patterns

Anti-PatternTime CostFix
Timer in .default RunLoop mode30+ min debugging scroll freezeUse .common mode
No state tracking on DispatchSourceTimerEXC_BAD_INSTRUCTION crash, hours to diagnoseUse SafeDispatchTimer wrapper
timer.cancel() while suspendedProduction crashresume() then cancel()
Timer on .global() queueRace conditions, intermittent crashesDedicated serial queue
Force-unwrapping timerCrash if timer already cancelledOptional check or state enum
Not clearing event handler before cancelPotential retain cycletimer.setEventHandler(handler: nil) then cancel
Timer retains target (selector API)Memory leak — deinit never calledUse block API with [weak self]
Creating timer without invalidating previousTimer accumulation, CPU wasteAlways invalidate/cancel before creating new
Timer on background thread without RunLoopTimer silently never firesTimer requires a RunLoop — use DispatchSourceTimer or AsyncTimerSequence for background work

Part 7: Pressure Scenarios

Scenario 1: "Just use Timer.scheduledTimer and move on"

Setup: Deadline approaching, need a repeating update every second.

Pressure: Timer is simpler than DispatchSourceTimer. "It's just a UI update timer, no need for GCD complexity."

Expected with skill: Choose Timer for simple UI updates — but add it to .common RunLoop mode so it survives scrolling. Only reach for DispatchSourceTimer when you need precision, background execution, or a custom queue.

Anti-pattern without skill: Using Timer.scheduledTimer with default .default mode → timer stops during scrolling → user reports "progress bar freezes when I scroll" → 30+ min debugging.

Pushback template: "Timer is the right choice for a UI update, but we need to add it to .common RunLoop mode. Without that, the timer stops every time the user scrolls. It's a 2-line change that prevents a guaranteed bug report."


Scenario 2: "The crash only happens sometimes, let's ship and fix later"

Setup: EXC_BAD_INSTRUCTION in production crash logs. Can't reproduce reliably in development.

Pressure: "It's rare. Users can reopen the app. We'll fix it in the next release."

Expected with skill: Recognize the crash signature as a DispatchSourceTimer state machine violation. All 4 crash patterns are deterministic — they happen every time the specific state transition occurs. The "intermittent" appearance comes from the state transition being timing-dependent, not the crash itself. Apply SafeDispatchTimer wrapper.

Anti-pattern without skill: Shipping without fix → crash rate compounds with user count → crash appears in App Store review metrics → rejection risk.

Pushback template: "This crash is deterministic — it happens every time the timer is in a specific state. The 'intermittent' part is just the timing of when that state occurs. SafeDispatchTimer is a drop-in replacement that eliminates all 4 crash patterns. It's a 15-minute fix that prevents a production crash."


Scenario 3: "Timer.invalidate() handles cleanup"

Setup: Timer being used in a view controller, calling invalidate() in deinit.

Pressure: "invalidate() is the standard cleanup pattern. It's in every tutorial."

Expected with skill: Recognize the retain cycle: Timer.scheduledTimer(timeInterval:target:selector:) retains its target. If the target is self (the view controller), and the view controller holds a strong reference to the timer, you have a retain cycle. deinit never gets called because the timer keeps self alive. Solution: use [weak self] with the block API, and invalidate in viewWillDisappear (not deinit).

Anti-pattern without skill: Timer retains self → deinit never called → invalidate never called → timer keeps firing → memory leak + accumulating timers → eventual crash or battery drain.

Pushback template: "The block-based Timer API with [weak self] is the fix. The selector-based API retains its target, which means our deinit never fires and invalidate() never gets called. We also need to move invalidate() to viewWillDisappear as a safety net."


Related Skills

  • axiom-timer-patterns-ref — API reference for Timer, DispatchSourceTimer, Combine Timer.publish, AsyncTimerSequence with lifecycle diagrams and platform availability
  • axiom-memory-debugging — Timer as Pattern 1 memory leak (Timer retains target, RunLoop retains Timer)
  • axiom-energy — Timer as energy drain pattern (tolerance, coalescing, event-driven alternatives)

Resources

WWDC: 2017-706

Skills: timer-patterns-ref, memory-debugging, energy, energy-ref

平台分布

Codex

35.67%
按下载量换算247

Claude

29.54%
按下载量换算204

Cursor

18.93%
按下载量换算131

Gemini CLI

10.2%
按下载量换算71

安全审计

Gen Agent Trust Hub

通过

Socket

通过

Snyk

通过

权限和风险

执行命令

安装流程涉及命令执行,可能通过 npx skills add https://github.com/charleswiltgen/axiom --skill axiom-timer-patterns 联网下载 Skill 或依赖。用户安装前应确认命令来源、仓库内容和执行环境。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。目前只有一个公开来源,建议同时核对源仓库。

继续浏览同类 Skills