PHP script as a cron job

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

Threaded View
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?


Re: PHP script as a cron job

Quoted text here. Click to load it

Yes. Ensure safe mode is off, and then you can use set_time_limit() to 0 to  
script killing. Call "php scriptname.php" from cron to launch it.

Quoted text here. Click to load it

If it's a server, why not try connecting to it and see if it times out? Then  
you'd know
if it's responding or not. If you're happy with the command line, and safe  
mode is off,
you can use exec() to run shell commands directly to kill it.


Re: PHP script as a cron job

Quoted text here. Click to load it

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 == '..')){
  $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.


Apologies for the ad below.

*** Free account sponsored by ***
*** Encrypt your Internet usage with a free VPN account from ***

Re: PHP script as a cron job

s wrote:
Quoted text here. Click to load it

flock a file in /tmp and fail if you don't get the flock.
Since the lock is handled by the kernel, it will die if the locking  
process dies.


Site Timeline