Skip to content

Instantly share code, notes, and snippets.

@pheisiph
Created February 20, 2012 14:33
Show Gist options
  • Save pheisiph/1869481 to your computer and use it in GitHub Desktop.
Save pheisiph/1869481 to your computer and use it in GitHub Desktop.
Daemonizing rake tasks using dtach
namespace :myapp do
namespace :mynamespace do
class MyProcessRunner
def self.basename
"task_name"
end
def self.socket
Rails.root.join("tmp", "sockets", "#{basename}.dtach")
# or write in tmp/pids, as its presence can be assumed?
end
def self.pid_file
Rails.root.join("tmp", "pids", "#{basename}.pid")
end
def self.write_pid
raise 'pid file exists!' if File.exists? pid_file
File.open(pid_file, 'w+') { |f| f.puts Process.pid }
end
def self.pid
File.read(pid_file)
end
def self.delete_pid
File.delete pid_file
end
def self.kill_process
exec "kill -s TERM #{pid}"
File.delete(pid_file)
end
end
desc 'run the task in the console as regular rake task'
task :run => :environment do
begin
MyProcessRunner.write_pid
tp = Some::Task::With::Loop.new #and sleep
tp.start
rescue
Rails.logger.error $!.backtrace.join("\n")
ensure
MyProcessRunner.delete_pid
end
end
desc "run the task as a daemon using dtach"
task :start => :environment do
begin
sh "dtach -n #{MyProcessRunner.socket} rake myapp:mynamespace:run"
rescue
puts $!.backtrace.join("\n")
end
end
desc "stop the dtached daemon"
task :stop => :environment do
MyProcessRunner.kill_process
end
desc 'attach the dtached daemon to the console'
task :attach => :environment do
exec "dtach -a #{MyProcessRunner.socket}"
end
desc 'restart the dtached daemon'
task :restart => [:environment, :stop, :start]
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment