Forum: Ruby Block execution of script while same script is already running

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
05b76b92415862cc4783d09a9009641b?d=identicon&s=25 MrBanabas@googlemail.com (Guest)
on 2008-12-17 10:45
(Received via mailing list)
Hi,

Does anybody no how I may achieve it:

Bob is starting script my_test.rb which runs a over an hour...
5 minutes later...
Alice is not knowing that Box has already started is and starts it
again.
Script should detect that it is already running and stop executing.

What is the best way to achieve this?

Thanks a lot.
E0d864d9677f3c1482a20152b7cac0e2?d=identicon&s=25 Robert Klemme (Guest)
on 2008-12-17 12:04
(Received via mailing list)
2008/12/17 MrBanabas@googlemail.com <MrBanabas@googlemail.com>:
> Bob is starting script my_test.rb which runs a over an hour...
> 5 minutes later...
> Alice is not knowing that Box has already started is and starts it
> again.
> Script should detect that it is already running and stop executing.
>
> What is the best way to achieve this?

There are solutions for this in the archives of this list.  You can
use an exclusive file lock on $0 as an example.

Kind regards

robert
E1d641bfe4071a5413bac781f06d3fd1?d=identicon&s=25 Sean O'halpin (sean)
on 2008-12-17 19:12
(Received via mailing list)
On Wed, Dec 17, 2008 at 9:37 AM, MrBanabas@googlemail.com
<MrBanabas@googlemail.com> wrote:
> What is the best way to achieve this?
>
> Thanks a lot.
>
> --
> Volker
>

Daniel Berger suggested the following technique (see thread starting
at ruby-talk:302489).

This is my version:

def single_instance(&block)
  if File.open($0).flock(File::LOCK_EX|File::LOCK_NB)
    block.call
  else
    warn "Script #{ $0 } is already running"
  end
end

single_instance do
  # your main code here
end

Regards,
Sean
This topic is locked and can not be replied to.