Faking Cron with PEAR Cache and date()

If you don’t have access to cron on your server, but you
want to run some php code periodically, this is a handy way of doing
that using output caching and the date function. This assumes you’ll be using PEAR’s Cache module. Here’s the code, and and explanation.

require_once( 'Cache/Output.php' );
$cache = new Cache_output('file', array('cache_dir'=>CACHE_DIR));
$cache_id = $cache->generateID( array( $_SERVER['SERVER_NAME'], date('Ymd'), floor(date('H') / 4) ) );

if ( $content = $cache->start($cache_id) )
{
//cache hit
echo $content;
}
else
{
//generate your output here

echo $cache->end()
}

Notice how we’re using the date function to generate our cache key. The first call to date with parameter ‘Ymd’ simply returns todays date as a string ‘20051220’. The next date call gets the hour as a number from 0 to 24, divides by 4, and uses floor() to make the result an integer. In effect, every four hours, we have a new cache key generated and the output is regenerated. By using different formats for the date, and different divisors, we can "schedule" our output generation at any interval.