Skip to content

Instantly share code, notes, and snippets.

@pigoz
Created September 14, 2011 19:59
Show Gist options
  • Save pigoz/1217612 to your computer and use it in GitHub Desktop.
Save pigoz/1217612 to your computer and use it in GitHub Desktop.
PidLock
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
@pigoz
Copy link
Author

pigoz commented Sep 14, 2011

@francescoagati: possiamo usare questo per non eseguire + rake task dello stesso tipo contemporaneamente.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment