Class: Zui::Scheduler

Inherits:
Object
  • Object
show all
Defined in:
lib/zui/scheduler.rb

Instance Method Summary collapse

Constructor Details

#initialize(evaluator:, on_error:) ⇒ Scheduler

Returns a new instance of Scheduler.



92
93
94
95
96
97
98
# File 'lib/zui/scheduler.rb', line 92

def initialize(evaluator:, on_error:)
  @evaluator = evaluator
  @on_error = on_error
  @tasks = []
  @lock = Mutex.new
  @started = false
end

Instance Method Details

#schedule(kind, interval: 0, immediate: false, &block) ⇒ Object

Raises:

  • (ArgumentError)


100
101
102
103
104
105
106
107
108
109
110
# File 'lib/zui/scheduler.rb', line 100

def schedule(kind, interval: 0, immediate: false, &block)
  raise ArgumentError, "task requires a block" unless block
  seconds = Float(interval)
  raise ArgumentError, "task interval must be positive" if kind != :async && !seconds.positive?
  task = Task.new(kind:, interval: seconds, immediate:, block:)
  @lock.synchronize do
    @tasks << task
    task.start(@evaluator, @on_error) if @started
  end
  task
end

#startObject



112
113
114
115
116
117
118
# File 'lib/zui/scheduler.rb', line 112

def start
  @lock.synchronize do
    @started = true
    @tasks.each { |task| task.start(@evaluator, @on_error) }
  end
  self
end

#stopObject



120
121
122
123
124
125
126
127
128
# File 'lib/zui/scheduler.rb', line 120

def stop
  tasks = @lock.synchronize do
    @started = false
    @tasks.dup
  end
  tasks.each(&:cancel)
  tasks.each { |task| task.join(1) }
  self
end

#tick(now = Time.now.to_f) ⇒ Object



130
131
132
133
134
# File 'lib/zui/scheduler.rb', line 130

def tick(now = Time.now.to_f)
  tasks = @lock.synchronize { @tasks.dup }
  tasks.each { |task| task.tick(now) }
  self
end