Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ruby preventing running script multiple times

Tags:

ruby

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.

like image 267
Karthi1234 Avatar asked May 31 '26 12:05

Karthi1234


2 Answers

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__
like image 194
Karthi1234 Avatar answered Jun 02 '26 01:06

Karthi1234


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.

like image 40
Eric Duminil Avatar answered Jun 02 '26 02:06

Eric Duminil