app.timer - 定时器 API
提供延迟执行和重复执行功能。
方法
app.timer.after(seconds, callback)
创建一次性延迟定时器。
参数:
seconds(number) - 延迟时间(秒),最小 0.01callback(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.1callback(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) - 定时器 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 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