forked from zammad/zammad
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbackground_services.rb
70 lines (55 loc) · 1.47 KB
/
background_services.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# Copyright (C) 2012-2022 Zammad Foundation, https://zammad-foundation.org/
class BackgroundServices
def self.available_services
BackgroundServices::Service.descendants
end
attr_reader :config
def initialize(config)
@config = Array(config)
end
def run
Rails.logger.debug 'Starting BackgroundServices...'
config.each do |service_config|
run_service service_config
end
Process.waitall
loop do
sleep 1
end
rescue Interrupt
nil
ensure
Rails.logger.debug('Stopping BackgroundServices.')
end
private
def run_service(service_config)
if !service_config.enabled?
Rails.logger.debug { "Skipping disabled service #{service_config.service.service_name}." }
return
end
service_config.service.pre_run
case service_config.start_as
when :fork
start_as_forks(service_config.service, service_config.workers)
when :thread
start_as_thread(service_config.service)
end
end
def start_as_forks(service, forks)
(1..forks).map do
Process.fork do
Rails.logger.debug { "Starting process ##{Process.pid} for service #{service.service_name}." }
service.new.run
rescue Interrupt
nil
end
end
end
def start_as_thread(service)
Thread.new do
Thread.current.abort_on_exception = true
Rails.logger.debug { "Starting thread for service #{service.service_name} in the main process." }
service.new.run
end
end
end