Mike Schilli's Friendly Neighborhood Perl Shop

CPAN Modules
Articles in English
Articles in German
Mike's Script Archive
English-Japanese Translation Trainer
Adventures with O'Reilly's Safari
10 Easy Steps to Become a California Driver
Unofficial perlmonks.com IRC Channel
My Collection of Outage Pages
Prisma (Computer Club Deutschland)
Mike's Monologues
Mike's Script Archive: CronDaemon.pm

CronDaemon.pm -- Utility module for crontab-triggered pseudo daemons


    CronDaemon.pm -- Utility module for crontab-triggered pseudo daemons




    use CronDaemon;


Sometimes instead of running a permanent daemon you want a script to kick in in regular intervals, do its job and then terminate. This way it's not susceptible to memory growth, unreclaimed file handles and other issues badly programmed scripts run into when run 24 hours a day without restart.

If you run a script e.g. every minute from the cron, however, and it takes more than 60 secs to complete, there's going to be 2 instances of the same script potentially interfering with each other.

Enter CronDaemon. It will make sure that at all times, there's only one instance of the script. If an instance hangs, and therefore prevents a script restart for a configurable number of rounds, the new instance will kill the old one and step in its place.


    use CronDaemon;
    my $cd = CronDaemon->new(pidfile => "/tmp/myapp_pid_file");
    if($cd->already_running()) {
        print "Another instance already running\n";
        exit 0;
    } else {
        print "Registering new instance\n";
    sleep(10);  # This is our application
    # PID file will be erased automatically if $cd goes out of scope

CronDaemon is Log::Log4perl enabled. If you turn on logging in the CronDaemon category, you'll see logging statements according to your Log::Log4perl settings.


Copyright 2002 by Mike Schilli, all rights reserved. This program is free software, you can redistribute it and/or modify it under the same terms as Perl itself.


2002, Mike Schilli <m@perlmeister.com>

Latest update: 20-Oct-2013