2

I have written ruby script which I put in cronjob and need to prevent running the same script if there is a process already running on the same script. Basically I am trying to prevent running duplicate process for the same script and if the script is not actually running then only it has to run.

I tried with flock but I think it locks file for writing purpose only. Like if any of the process already writing a file then no other process can write the same file.

Somehow I managed this by checking the running process if any contians the script name if not then only the process will start. But wondering is there any builtin module in Ruby which can take care of this thing.

2 Answers 2

7

Thanks @Eric . But I was managed to get this working without installing any additional gems.

if $0 == __FILE__
  if File.new(__FILE__).flock(File::LOCK_EX | File::LOCK_NB)
    validation()
  else
    raise "Another process running for the same script."
  end
end

__END__
Sign up to request clarification or add additional context in comments.

2 Comments

Good to know. It also seems to work fine when the process is killed or after a reboot.
Yep. It should work even when you kill the process or reboot the server.
5

This PID file gem could help you.

Here's an example :

require 'pidfile'

pf = PidFile.new
puts "LAUNCHING SCRIPT"
loop do
  sleep 1
  puts "+1"
end

Launching it once works fine.

Trying to launch it twice returns :

pidfile.rb:39:in `initialize': Process (lock.rb - 17724) is already running. (PidFile::DuplicateProcessError)
    from lock.rb:3:in `new'
    from lock.rb:3:in `<main>'

Note: The PID file is written in /tmp by default. It's not a problem on Ubuntu because /tmp is cleaned at reboot.

It could be a problem on other systems (e.g. RHEL) on which /tmp is cleaned daily.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.