Class: HaveAPI::Fs::Worker

Inherits:
Object
  • Object
show all
Defined in:
lib/haveapi/fs/worker.rb

Overview

Base class for classes that perform some regular work in a separate thread.

Direct Known Subclasses

Cache, Cleaner

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(fs) ⇒ Worker

Returns a new instance of Worker.

Parameters:



9
10
11
12
13
14
15
# File 'lib/haveapi/fs/worker.rb', line 9

def initialize(fs)
  @fs = fs
  @run = true
  @pipe_r, @pipe_w = IO.pipe
  @runs = 0
  @mutex = Mutex.new
end

Instance Attribute Details

#runsObject (readonly)

Returns the value of attribute runs.



6
7
8
# File 'lib/haveapi/fs/worker.rb', line 6

def runs
  @runs
end

Instance Method Details

#last_timeObject

The time when the work method was last run.



48
49
50
# File 'lib/haveapi/fs/worker.rb', line 48

def last_time
  @mutex.synchronize { @last_time }
end

#next_timeObject

The time when the work method will be run next.



53
54
55
# File 'lib/haveapi/fs/worker.rb', line 53

def next_time
  @mutex.synchronize { @next_time }
end

#startObject

Start the work thread.



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/haveapi/fs/worker.rb', line 18

def start
  @thread = Thread.new do
    @mutex.synchronize { @next_time = Time.now + start_delay }
    wait(start_delay)

    while @run do
      @fs.synchronize { work }

      @runs += 1
      @mutex.synchronize do
        @last_time = Time.now
        @next_time = @last_time + work_period
      end

      wait(work_period)
    end
  end
end

#stopObject

Stop and join the work thread.



38
39
40
41
42
43
44
45
# File 'lib/haveapi/fs/worker.rb', line 38

def stop
  @run = false
  @pipe_w.write('CLOSE')
  @thread.join

  @pipe_r.close
  @pipe_w.close
end