service.lua
- local event = require('event')
- local s = require('serialization').serialize
- local service = {}
- local function step_coroutine(c)
- local t = {coroutine.resume(c)}
- if not t[1] then
- if coroutine.status(c) == 'dead' then
- return false
- else
- print(debug.traceback(c))
- error(t[2], 0)
- end
- end
- return true
- end
- function service.periodic(period, f, env)
- local t
- local function service_coroutine()
- while true do
- local c = coroutine.create(f)
- while true do
- if not step_coroutine(c) then
- break
- end
- coroutine.yield()
- end
- end
- end
- function env.start()
- if t then
- return
- end
- local c = coroutine.create(service_coroutine)
- local function step()
- step_coroutine(c)
- end
- t = event.timer(period, step, math.huge)
- end
- function env.stop()
- if not t then
- return
- end
- event.cancel(t)
- end
- function env.status()
- if t then
- print('running')
- else
- print('stopped')
- end
- end
- end
- return service
example-service.lua
- local service = require('service')
- -- [...]
- function tick()
- clear_whole_db()
- export_relevant_items()
- end
- service.periodic(10, tick, _ENV)