timer.rb 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. # Model and handle the clients of the server
  2. class Timer
  3. attr_reader :id
  4. attr_reader :name
  5. def initialize(name, &block)
  6. @name = name
  7. @id = nil
  8. @block = block
  9. end
  10. def set(value = 1.0, interval = 1.0)
  11. Woe::Server.set_timer(@id, value, interval);
  12. end
  13. def start(value = 1.0, interval = 1.0)
  14. @id = Woe::Server.new_timer()
  15. return @id if (@id < 0)
  16. self.set(value, interval);
  17. return @id
  18. end
  19. def self.add(name, value, interval, &block)
  20. timer = Timer.new(name, &block)
  21. return nil if timer.start(value, interval) < 0
  22. @timers ||= {}
  23. @timers[timer.id] = timer
  24. end
  25. def self.get(id)
  26. @timers ||= {}
  27. @timers[id]
  28. end
  29. def self.get_by_name(name)
  30. @timers ||= {}
  31. @timers.select { |t| t.name == name }.first
  32. end
  33. def self.remove(id)
  34. @timers[id] = nil
  35. end
  36. def on_timer()
  37. @block.call
  38. end
  39. def self.on_timer(id)
  40. timer = self.get(id)
  41. timer.on_timer if timer
  42. end
  43. end
  44. log "Mruby timer script loaded OK."