Class: Zui::Task

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(kind:, interval:, immediate:, block:) ⇒ Task

Returns a new instance of Task.



7
8
9
10
11
12
13
14
15
16
# File 'lib/zui/scheduler.rb', line 7

def initialize(kind:, interval:, immediate:, block:)
  @kind = kind
  @interval = interval
  @immediate = immediate
  @block = block
  @mutex = Mutex.new
  @condition = ConditionVariable.new
  @cancelled = false
  @thread = nil
end

Instance Attribute Details

#blockObject (readonly)

Returns the value of attribute block.



5
6
7
# File 'lib/zui/scheduler.rb', line 5

def block
  @block
end

#intervalObject (readonly)

Returns the value of attribute interval.



5
6
7
# File 'lib/zui/scheduler.rb', line 5

def interval
  @interval
end

#kindObject (readonly)

Returns the value of attribute kind.



5
6
7
# File 'lib/zui/scheduler.rb', line 5

def kind
  @kind
end

Instance Method Details

#cancelObject



34
35
36
37
38
39
40
# File 'lib/zui/scheduler.rb', line 34

def cancel
  @mutex.synchronize do
    @cancelled = true
    @condition.broadcast
  end
  self
end

#cancelled?Boolean

Returns:

  • (Boolean)


59
60
61
# File 'lib/zui/scheduler.rb', line 59

def cancelled?
  @mutex.synchronize { @cancelled }
end

#join(timeout = nil) ⇒ Object



42
43
44
45
46
# File 'lib/zui/scheduler.rb', line 42

def join(timeout = nil)
  thread = @mutex.synchronize { @thread }
  thread.join(timeout) if thread && thread != :cooperative
  self
end

#start(evaluator, on_error) ⇒ Object



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/zui/scheduler.rb', line 18

def start(evaluator, on_error)
  @mutex.synchronize do
    return self if @cancelled || @thread
    if Object.const_defined?(:Thread)
      @thread = Thread.new { run(evaluator, on_error) }
      @thread.name = "zui-#{kind}" if @thread.respond_to?(:name=)
    else
      @thread = :cooperative
      @evaluator = evaluator
      @on_error = on_error
      @next_due = Time.now.to_f + ((kind == :async || @immediate) ? 0 : interval)
    end
  end
  self
end

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



48
49
50
51
52
53
54
55
56
57
# File 'lib/zui/scheduler.rb', line 48

def tick(now = Time.now.to_f)
  return unless @thread == :cooperative || !Object.const_defined?(:Thread)
  return if cancelled? || now < @next_due
  invoke(@evaluator, @on_error)
  if kind == :every
    @next_due = now + interval
  else
    cancel
  end
end