app.timer - 定时器 API

提供延迟执行和重复执行功能。

方法

app.timer.after(seconds, callback)

创建一次性延迟定时器。

参数:

  • seconds (number) - 延迟时间(秒),最小 0.01
  • callback (function) - 延迟后执行的回调函数

返回值: string, error - 定时器 ID

-- 3 秒后执行
local id, err = app.timer.after(3, function()
    app.notification.show("提醒", "3 秒已到!")
end)

-- 0.5 秒后执行
app.timer.after(0.5, function()
    app.log.info("短暂延迟后执行")
end)

app.timer.start(seconds, callback)

创建重复定时器。

参数:

  • seconds (number) - 执行间隔(秒),最小 0.1
  • callback (function) - 每次触发时执行的回调函数

返回值: string, error - 定时器 ID

-- 每 5 秒执行一次
local id = app.timer.start(5, function()
    app.log.info("心跳: " .. os.date())
end)

-- 需要时停止
app.timer.stop(id)

app.timer.stop(id)

取消指定定时器。

参数:

  • id (string) - 定时器 ID

返回值: boolean, error

local ok, err = app.timer.stop(id)

app.timer.stopAll()

取消当前插件的所有定时器。

返回值: boolean

app.timer.stopAll()

app.timer.list()

列出当前插件的活跃定时器。

返回值: array<table> - 每项包含:

  • id (string) - 定时器 ID
  • type (string) - 类型: "once""repeating"
  • interval (number) - 间隔/延迟(秒)
  • repeats (boolean) - 是否重复
  • remaining (number, 仅一次性) - 剩余时间(秒)
local timers = app.timer.list()
for _, tmr in ipairs(timers) do
    app.log.info(tmr.id .. ": " .. tmr.type .. " interval=" .. tmr.interval)
end

说明

  • 每个插件最多 100 个定时器
  • 一次性定时器执行后自动移除
  • 定时器在插件卸载时自动取消
  • 回调在插件执行队列上调用(线程安全)
  • after() 最小延迟 0.01 秒,every() 最小间隔 0.1 秒

示例

定时检查文件变化

local checkTimerId = nil

function MyPlugin:handleStartMonitor(context)
    local dir = context.currentDirectory
    local lastCount = 0

    checkTimerId = app.timer.start(10, function()
        local files = app.file.list(dir)
        if files and #files ~= lastCount then
            local diff = #files - lastCount
            if diff > 0 then
                app.notification.show("新文件", "发现 " .. diff .. " 个新文件")
            end
            lastCount = #files
        end
    end)

    app.notification.show("监控", "开始监控: " .. dir)
end

function MyPlugin:handleStopMonitor(context)
    if checkTimerId then
        app.timer.stop(checkTimerId)
        checkTimerId = nil
        app.notification.show("监控", "已停止监控")
    end
end

延迟关闭进度条

function MyPlugin:handleProcess(context)
    app.progress.show("处理中", {message = "正在处理..."})

    -- 模拟处理
    for i = 1, 100 do
        app.progress.update(i, "步骤 " .. i .. "/100")
        app.thread.sleep(0.05)
    end

    app.progress.update(100, "完成!")

    -- 1 秒后自动关闭进度条
    app.timer.after(1, function()
        app.progress.hide()
    end)
end
开发者文档
使用帮助
使用说明 脚本菜单 常见问题
脚本开发
开发指南
插件开发
快速开始 开发指南 示例插件
API 参考
概览 API 查询 插件信息 日志 Finder 上下文 插件设置 国际化
UI 与交互
对话框 进度条 系统通知 选择器 WebView 状态栏 Dock
文件与路径
文件操作 路径工具 Finder 操作 废纸篓 扩展属性 元数据 文件监听
数据格式
JSON Plist CSV XML PDF 图片
文本与编码
字符串 正则表达式 日期时间 颜色 加密编码
系统
Shell 命令 进程管理 应用管理 系统信息 AppleScript 快捷指令
系统信息
网络信息 电源/电池 屏幕/外观 音频控制 蓝牙设备 位置服务
网络
HTTP 请求 WebSocket URL 工具
输入与剪贴板
键盘模拟 鼠标模拟 全局热键 剪贴板 窗口管理
存储
SQLite Keychain UserDefaults
媒体
文字识别 二维码
工具
归档 类型标识 分享 定时器 防休眠 并发/协程