Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Single Instance Ruby App?

Tags:

ruby

If I've got a Ruby program, and I only want one instance of it to be able to run at a time, what are best[1] ways of accomplishing that? I've tried Googling but it thinks I'm looking for singleton-related information making it hard to find what I'm actually looking for.

[1] best= shortest, simplest, self-explanitory, doesn't require extra gems

like image 700
Jeff Welling Avatar asked Mar 15 '26 21:03

Jeff Welling


1 Answers

From http://rosettacode.org/wiki/Determine_if_only_one_instance_is_running#Ruby

def main
  puts "first instance"
  sleep 20
  puts :done
end

if $0 == __FILE__
  if File.new(__FILE__).flock(File::LOCK_EX | File::LOCK_NB)
    main
  else
    raise "another instance of this program is running"
  end
end
like image 118
Robert Harvey Avatar answered Mar 19 '26 02:03

Robert Harvey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!