local serialization=require("serialization") local computer=require("computer") local T={FILE="/etc/yaru-tasks.cfg"} function T.load() local f=io.open(T.FILE) if not f then return{}end local ok,t=pcall(serialization.unserialize,f:read("*a")) f:close() return ok and type(t)=="table"and t or{} end function T.save(list) local f=io.open(T.FILE,"w") if f then f:write(serialization.serialize(list));f:close()end end function T.describe(task) local n=task.when:match("^every (%d+)") if n then return"every "..n.." min"end local hm=task.when:match("^at (%d+:%d+)") if hm then return"daily at "..hm end return"at login" end function T.run(Y,task) task.last=computer.uptime() task.result="running" local cmd=task.cmd require("thread").create(function() local ok,a,b=pcall(require("shell").execute,cmd.." >>/tmp/tasks.log") task.result=(ok and a~=false)and("ok "..Y.date("%H:%M"))or("failed "..Y.date("%H:%M")) local list=T.load() for _,t2 in ipairs(list)do if t2.cmd==task.cmd and t2.when==task.when then t2.result,t2.last,t2.lastDay=task.result,task.last,task.lastDay end end T.save(list) if not(ok and a~=false)or task.notify then Y.notify("Task “"..task.name.."”",task.result..(ok and""or(": "..tostring(a))),{actionLabel="Log", action=function()Y.launch("editor","/tmp/tasks.log")end}) end end):detach() end function T.tick(Y,login) local list=T.load() local hm=Y.date("%H:%M") local up=computer.uptime() local changed=false for _,task in ipairs(list)do if task.on then local every=tonumber(task.when:match("^every (%d+)")or"") local at=task.when:match("^at (%d+:%d+)") local due=(login and task.when=="login") or(every and(not task.last or task.last>up or up-task.last>=every*60-5)) or(at and at==hm and task.lastDay~=Y.date("%Y-%m-%d")) if due then if at then task.lastDay=Y.date("%Y-%m-%d")end T.run(Y,task) changed=true end end end if changed then T.save(list)end end return T