Last active
August 29, 2015 14:08
-
-
Save fadhlirahim/41c63b56fad338bcb157 to your computer and use it in GitHub Desktop.
Write a PID file in Rails
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Sample module you can include in a rake task that checks a pid file before running | |
# Usage: | |
# require 'task' | |
# | |
# class Job | |
# include Task | |
# end | |
module Task | |
def self.included(base) | |
base.extend(ClassMethods) | |
end | |
def ClassMethods | |
def run | |
exit! if running? | |
`echo foo` | |
done! | |
end | |
def pid_file | |
return if Rails.env.test? | |
Rails.root.join('tmp', 'task.pid') | |
end | |
def write_pid | |
return if Rails.env.test? | |
File.open pid_file, "w" do |f| | |
f.write Process.pid | |
end | |
end | |
def running! | |
return if Rails.env.test? | |
`touch #{pid_file}` | |
write_pid | |
end | |
def done! | |
return if Rails.env.test? | |
`rm #{pid_file}` | |
end | |
def pid | |
return if Rails.env.test? | |
`cat #{pid_file}` | |
end | |
def running? | |
return if Rails.env.test? | |
File.exists?(pid_file) | |
end | |
end | |
end | |
# Sample rake task library | |
namespace :job do | |
class Job | |
include Task | |
end | |
desc 'Run a task' | |
task run: [:environment] do | |
Job.run | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment