Created
September 14, 2011 19:59
-
-
Save pigoz/1217612 to your computer and use it in GitHub Desktop.
PidLock
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
class PidLock | |
def initialize(name, &block) | |
@name = name | |
if can_execute? | |
set_running | |
block.call | |
else | |
puts "the pidfile #{pidfile} is locked by process #{current_pid}" | |
end | |
end | |
def can_execute? | |
return true if current_pid == 0 | |
Process.kill(0, current_pid) | |
false | |
rescue Errno::ESRCH, RangeError => e | |
true | |
end | |
def current_pid | |
timeout ||= 2 | |
IO.read(pidfile).to_i | |
rescue Errno::ENOENT => e | |
File.open(pidfile, 'w') | |
retry if (timeout -= 1) > 0 | |
end | |
def set_running | |
File.open(pidfile, 'w') {|f| f.write("#{Process.pid}") } | |
nil | |
end | |
def pidfile | |
"#{@name}.pid" | |
end | |
end | |
namespace "workers" do | |
task "prova" do |t| | |
PidLock.new(t.name) do | |
sleep(10) | |
end | |
end | |
end | |
# pigoz@NAVI ~/dev » rake workers:prova & | |
# [1] 1083 | |
# pigoz@NAVI ~/dev » rake workers:prova | |
# the pidfile workers:prova.pid is locked by process 1083 | |
# pigoz@NAVI ~/dev » | |
# [1] + 1083 done rake workers:prova |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@francescoagati: possiamo usare questo per non eseguire + rake task dello stesso tipo contemporaneamente.