One might like to do flock manually or use a CPAN module. Meta::cpan is equipped with many flock modules. The Mutex module was made to work realiably with parallelization, supports threads and processes, including nested sessions.

The path option to Mutex constructs a Mutex::Flock object. One may specify the script path or a temporary path. Typically, the system flock requires read-write access to work. Thus, the Mutex module does a check and emits an error if the path isn't writeable by the calling process-userid.

use Mutex; my $mutex = Mutex->new( path => $0 ); # choose $0 or tmp path my $mutex = Mutex->new( path => "/tmp/db.lock" ); # The script terminates after some time if a previous # instance is still running with a held lock. exit unless $mutex->timedwait( 5 ); # seconds # Has exclusive lock at this point. Due to using flock, # the lock is released no matter how the process dies, # even if omitting $mutex->unlock. # Do DB insert here. $mutex->unlock; # Do other things, optionally. ...

The example lacks logic for storing the item to insert into a state file, in the event unable to obtain an exclusive lock. Running again with exclusive lock inserts pending items.

my $state_mutex = Mutex->new( path => "/tmp/state.lock" ); $state_mutex->enter( sub { # Unable to obtain exclusive lock, then append pending inserts # to a state file. Otherwise, read pending items, insert into DB, # then unlink or empty the state file. } );

Regards, Mario


In reply to Re^2: perl script and queue by marioroy
in thread perl script and queue by k_manimuthu

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.