app.timer - 定时器 API
提供延迟执行和重复执行功能。
权限:L1 标准 — 需在
permissions中声明("timer")
方法
app.timer.after(seconds, callback)
创建一次性延迟定时器。
参数:
seconds(number) - 延迟时间(秒),最小 0.01callback(function) - 延迟后执行的回调函数
返回值: timerHandle - 定时器句柄;失败时返回 nil, error
返回的是句柄表,不是字符串 ID。 拿它去拼字符串会报
attempt to concatenate a table value。它的方法:stop()。
-- 3 秒后执行
local t, 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.1callback(function) - 每次触发时执行的回调函数
返回值: timerHandle - 定时器句柄;失败时返回 nil, error
返回的是句柄表,不是字符串 ID。 停止用
t:stop(),app.timer.stopAll()才是把当前插件的全部停掉。
-- 每 5 秒执行一次
local t = app.timer.start(5, function()
app.log.info("心跳: " .. os.date())
end)
-- 需要时停止
t:stop()
handle:stop()
取消指定定时器。
返回值: boolean, error
local ok, err = t:stop()
app.timer.stopAll()
取消当前插件的所有定时器。
返回值: boolean
app.timer.stopAll()
app.timer.list()
列出当前插件的活跃定时器。
返回值: array<table> - 每项包含:
id(string) - 定时器 IDtype(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 checkTimer = nil
function MyPlugin:handleStartMonitor(context)
local dir = context.currentDirectory
local lastCount = 0
checkTimer = 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 checkTimer then
checkTimer:stop()
checkTimer = nil
app.notification.show("监控", "已停止监控")
end
end
延迟关闭进度条
function MyPlugin:handleProcess(context)
local p = app.progress.create({title = "处理中", message = "正在处理..."})
-- 模拟处理
for i = 1, 100 do
p:update(i, "步骤 " .. i .. "/100")
app.thread.sleep(0.05)
end
p:update(100, "完成!")
-- 1 秒后自动关闭进度条
app.timer.after(1, function()
p:close()
end)
end