You are here: Re: PHP script as a cron job « PHP Programming Language « IT news, forums, messages
Re: PHP script as a cron job

Posted by s on 03/03/06 02:48

On Thu, 02 Mar 2006 15:18:43 -0500, Pol <Pol@nospam.com> wrote:

>Can php scripts be initiated as a cron jobs running indefinately in a
>loop performing a task?
>
>Any recommendations for writing a php script that will run as an unix
>server process that will run indefinitely once it starts?
>
>If cron starts it every 10 minutes. How can I check if I my process is
>running and then end if an instance is already running?

One approach is to have your script write a pid file, and check for
the presence of pid files from other instances of itself.

There are a few different ways you can use the pid file; here is some
code from a daemon that I have. This code writes a pid file for this
instance, then goes looking to see what other pid files exist. If the
create time of any given pid file is more than 12 hours old, the old
process is killed.

My goal here was to ensure that no running instance had been alive for
more than 12 hours (I had my reasons). But you could easily rework the
logic to, for example, prevent multiple instances from running at the
same time.

<?
#Write a pid file
touch('pidfiles/' . getmypid());

#Look for other processes
$dir = opendir('pidfiles') or die("Can't open PID directory\n");
while(($filename = readdir($dir)) !== false){
if(($filename == '.') || ($filename == '..')){
continue;
}
$time = filectime('pidfiles/' . $filename);
if($time < (time() - 43200)){
#Kill off the old process
`kill -9 $filename`;
unlink('pidfiles/' . $filename);
}
}

// Do your daemon stuff here...

#Remove our own pid file
unlink('pidfiles/' . getmypid());
?>

If you use this approach, don't forget that your script should remove
its own pid file if/when it finishes running cleanly, and it should
remove the pid file of any other process that it kills off.

hth

--
<s@guerril.la.ape> (to email, remove .ape)
Apologies for the ad below.
--

*** Free account sponsored by SecureIX.com ***
*** Encrypt your Internet usage with a free VPN account from http://www.SecureIX.com ***

 

Navigation:

[Reply to this message]


Удаленная работа для программистов  •  Как заработать на Google AdSense  •  England, UK  •  статьи на английском  •  PHP MySQL CMS Apache Oscommerce  •  Online Business Knowledge Base  •  DVD MP3 AVI MP4 players codecs conversion help
Home  •  Search  •  Site Map  •  Set as Homepage  •  Add to Favourites

Copyright © 2005-2006 Powered by Custom PHP Programming

Сайт изготовлен в Студии Валентина Петручека
изготовление и поддержка веб-сайтов, разработка программного обеспечения, поисковая оптимизация