spacepaste

service.lua

  1.  
  2. local event = require('event')
  3. local s = require('serialization').serialize
  4. local service = {}
  5. local function step_coroutine(c)
  6. local t = {coroutine.resume(c)}
  7. if not t[1] then
  8. if coroutine.status(c) == 'dead' then
  9. return false
  10. else
  11. print(debug.traceback(c))
  12. error(t[2], 0)
  13. end
  14. end
  15. return true
  16. end
  17. function service.periodic(period, f, env)
  18. local t
  19. local function service_coroutine()
  20. while true do
  21. local c = coroutine.create(f)
  22. while true do
  23. if not step_coroutine(c) then
  24. break
  25. end
  26. coroutine.yield()
  27. end
  28. end
  29. end
  30. function env.start()
  31. if t then
  32. return
  33. end
  34. local c = coroutine.create(service_coroutine)
  35. local function step()
  36. step_coroutine(c)
  37. end
  38. t = event.timer(period, step, math.huge)
  39. end
  40. function env.stop()
  41. if not t then
  42. return
  43. end
  44. event.cancel(t)
  45. end
  46. function env.status()
  47. if t then
  48. print('running')
  49. else
  50. print('stopped')
  51. end
  52. end
  53. end
  54. return service
  55.  

example-service.lua

  1.  
  2. local service = require('service')
  3. -- [...]
  4. function tick()
  5. clear_whole_db()
  6. export_relevant_items()
  7. end
  8. service.periodic(10, tick, _ENV)
  9.