HowTo run Redmine as a Windows service (win32-service + taskill approach) » History » Version 3

Etienne Massip, 2012-06-29 15:44

1 1 Etienne Massip
h1. HowTo run Redmine as a Windows service (@win32-service@ + @taskill@ approach)
2 1 Etienne Massip
3 1 Etienne Massip
* @gem install win32-service@
4 1 Etienne Massip
* drop below Ruby code in a @service.rb@ file and update @REDMINE_DIR@ path to fit your Redmine installation
5 3 Etienne Massip
* create the service, for example with @"sc":http://msdn.microsoft.com/en-us/library/cc990289.aspx create redmine binPath= "C:\Ruby193\bin\rubyw -C D:\redmine\ service.rb"@ where ??D:\redmine\?? is the path of the directory where the ??service.rb?? file is located and ??C:\Ruby193?? your Ruby installation path
6 1 Etienne Massip
7 1 Etienne Massip
<pre><code class="ruby">
8 1 Etienne Massip
REDMINE_DIR = 'D:\redmine'
9 1 Etienne Massip
LOG_FILE = "#{REDMINE_DIR}\\log\\service.log"
10 1 Etienne Massip
11 1 Etienne Massip
begin
12 1 Etienne Massip
  require 'win32/daemon'
13 1 Etienne Massip
  include Win32
14 1 Etienne Massip
15 1 Etienne Massip
  class RedmineService < Daemon
16 1 Etienne Massip
17 1 Etienne Massip
    def service_init
18 1 Etienne Massip
      File.open(LOG_FILE, 'a'){ |f| f.puts "Initializing service #{Time.now}" } 
19 1 Etienne Massip
20 1 Etienne Massip
      @server_pid = Process.spawn 'ruby script/rails s -e production', :chdir => REDMINE_DIR, :err => [LOG_FILE, 'a']
21 1 Etienne Massip
    end
22 1 Etienne Massip
23 1 Etienne Massip
    def service_main
24 1 Etienne Massip
      File.open(LOG_FILE, 'a'){ |f| f.puts "Service is running #{Time.now} with pid #{@server_pid}" }
25 1 Etienne Massip
      while running?
26 1 Etienne Massip
        sleep 10
27 1 Etienne Massip
      end
28 1 Etienne Massip
    end
29 1 Etienne Massip
30 1 Etienne Massip
    def service_stop
31 1 Etienne Massip
      File.open(LOG_FILE, 'a'){ |f| f.puts "Stopping server thread #{Time.now}" }
32 1 Etienne Massip
      system "taskkill /PID #{@server_pid} /T /F"
33 1 Etienne Massip
      Process.waitall
34 1 Etienne Massip
      File.open(LOG_FILE, 'a'){ |f| f.puts "Service stopped #{Time.now}" }
35 1 Etienne Massip
      exit!
36 1 Etienne Massip
    end
37 1 Etienne Massip
  end
38 1 Etienne Massip
39 1 Etienne Massip
  RedmineService.mainloop
40 1 Etienne Massip
41 1 Etienne Massip
rescue Exception => e
42 1 Etienne Massip
  File.open(LOG_FILE,'a+'){ |f| f.puts " ***Daemon failure #{Time.now} exception=#{e.inspect}\n#{e.backtrace.join($/)}" }
43 1 Etienne Massip
  raise
44 1 Etienne Massip
end
45 1 Etienne Massip
</code></pre>