Find programmers and grapic design experts at ScriptLance.com
<? DEW-CODE.COM  
Dew-Code
Welcome, Guest
Please Login or Register.    Lost Password?
Re:Using PHP to write command line scripts... (1 viewing) (1) Guest
Post your PHP related questions or observations here. Code snippets are always welcome.
Go to bottom Post Reply Favoured: 0
TOPIC: Re:Using PHP to write command line scripts...
#394
Dewed (User)
Administrator
Posts: 229
graph
User Offline Click here to see the profile of this user
Dew-Code.com
Re:Using PHP to write command line scripts... 4 Months, 3 Weeks ago Karma: 7  
When running PHP from cron, I've always thought its a good idea to create a lockfile, to prevent the script from running twice. For example a cron that is ran every minute, might occasionally take longer than a minute to complete. Meanwhile, you might occasionally need to override the lockfile, for example the script failed midway, and never removed the lockfile. To help with those scenerios, here is what I call my PHP cron template. I hope you find it useful.

Code:

#!/usr/bin/php -q <?php // config $lockfile = './'. $PHP_SELF .'.lock'; // lockfile name //how many minutes to just sit there before removing a stale lockfile and trying again //in case of failure on prior run $hardstart = 5; // end config ////////////////////////////////////////// //is lockfile stale ? $seconds = $hardstart * 60; if (file_exists("$lockfile")){ if (file_exists("$lockfile") && ((time() - filemtime("$lockfile")) > $seconds)) { if (unlink("$lockfile")){ $del = $del + 1; echo "Deleted: $lockfile "; } } else { echo "\n".'last batch is still running. Exiting '."\n"; die(); } } else { // create lockfile and start fetching $handle = fopen("$lockfile", "w"); $stamp = date("YmdHis"); fwrite($handle , $stamp); fclose($handle); // put the rest of your script here // remove the lockfile just before exiting ... unlink("$lockfile"); } // die() is preferable to exit() on command line scripts, while very similar // die() halts processing and immdediatly frees the resources, exit() actually // continues to be parsed, and only frees resources afterwards. die(); ?>
 
Report to moderator   Logged Logged  
 
Nothing to it but to Dew it !
Dew-Code.com
  The administrator has disabled public write access.
      Topics Author Date
    thread link
Using PHP to write command line scripts...
Dewed 2008/05/31 22:21
    thread link
thread linkthread link Re:Using PHP to write command line scripts...
Dewed 2008/07/11 11:12
Go to top Post Reply
Powered by FireBoardget the latest posts directly to your desktop

Newsflash

Sign up for PayPal and start accepting credit card payments instantly.
Copyright Dew-Code 2008