Karthi1234
Karthi1234

Reputation: 1017

ruby preventing running script multiple times

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.

Upvotes: 2

Views: 578

Answers (2)

Karthi1234
Karthi1234

Reputation: 1017

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__

Upvotes: 7

Eric Duminil
Eric Duminil

Reputation: 54223

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.

Upvotes: 5

Related Questions