Class: Tina4::Service

Inherits:
Object
  • Object
show all
Defined in:
lib/tina4/service.rb

Overview

Base class for class-based background services managed by ServiceRunner. Cross-framework parity with PHP ‘Tina4Service` and the same shape the documentation has long taught.

class EmailQueueWorker < Tina4::Service
  def run
    until should_stop?
      process_next_job
      sleep 1
    end
  end
end

Tina4::ServiceRunner.register_service("emails", EmailQueueWorker.new)
Tina4::ServiceRunner.start

Subclasses MUST override #run. Optionally override #stop for custom shutdown behaviour but always call ‘super` so the internal flag gets set — the default #should_stop? reads from it.

Instance Method Summary collapse

Constructor Details

#initializeService

Returns a new instance of Service.



28
29
30
# File 'lib/tina4/service.rb', line 28

def initialize
  @running = true
end

Instance Method Details

#runObject

Main work loop — subclasses MUST override.

Raises:

  • (NotImplementedError)


33
34
35
# File 'lib/tina4/service.rb', line 33

def run
  raise NotImplementedError, "#{self.class}#run must be implemented by the subclass"
end

#should_stop?Boolean

Returns true once #stop has been called. Use inside #run loops as the exit condition:

def run
  until should_stop?
    # do work
  end
end

Returns:

  • (Boolean)


50
51
52
# File 'lib/tina4/service.rb', line 50

def should_stop?
  !@running
end

#stopObject

Signal this service to stop. The next ‘should_stop?` check returns true.



38
39
40
# File 'lib/tina4/service.rb', line 38

def stop
  @running = false
end

#to_procObject

Return a callable that ServiceRunner can register. Used by ServiceRunner.register_service under the hood.



56
57
58
# File 'lib/tina4/service.rb', line 56

def to_proc
  method(:run).to_proc
end