PHP check if a timestamp matches a given cron schedule

desktop:~$ php -a
Interactive shell

php > echo time();
1319362432
php > 

Above is an example of a given timestamp.

And a cron schedule can look like this 0 5 * * * - which means run everyday at 5 hours and 0 minutes.

Now in a php application you may need to test if a given timestamp , say 1319362432 matches a given cron schedule like 0 5 * * *.

Here is a quick php function that can do this task.

/**
	Test if a timestamp matches a cron format or not
	//$cron = '5 0 * * *';
*/
function is_time_cron($time , $cron) 
{
    $cron_parts = explode(' ' , $cron);
    if(count($cron_parts) != 5)
    {
    	return false;
    }
    
    list($min , $hour , $day , $mon , $week) = explode(' ' , $cron);
    
    $to_check = array('min' => 'i' , 'hour' => 'G' , 'day' => 'j' , 'mon' => 'n' , 'week' => 'w');
    
    $ranges = array(
    	'min' => '0-59' ,
    	'hour' => '0-23' ,
    	'day' => '1-31' ,
    	'mon' => '1-12' ,
    	'week' => '0-6' ,
    );
    
    foreach($to_check as $part => $c)
    {
    	$val = $$part;
    	$values = array();
    	
    	/*
    		For patters like 0-23/2
    	*/
    	if(strpos($val , '/') !== false)
    	{
    		//Get the range and step
    		list($range , $steps) = explode('/' , $val);
    		
    		//Now get the start and stop
    		if($range == '*')
    		{
    			$range = $ranges[$part];
    		}
    		list($start , $stop) = explode('-' , $range);
    			
			for($i = $start ; $i <= $stop ; $i = $i + $steps)
			{
				$values[] = $i;
			}
    	}
    	/*
    		For patters like :
    		2
    		2,5,8
    		2-23
    	*/
    	else
    	{
    		$k = explode(',' , $val);
    		
    		foreach($k as $v)
    		{
    			if(strpos($v , '-') !== false)
    			{
    				list($start , $stop) = explode('-' , $v);
    			
					for($i = $start ; $i <= $stop ; $i++)
					{
						$values[] = $i;
					}
    			}
    			else
    			{
    				$values[] = $v;
    			}
    		}
    	}
    	
    	if ( !in_array( date($c , $time) , $values ) and (strval($val) != '*') ) 
		{
			return false;
		}
    }
    
    return true;
}

var_dump(time() , '0 5 * * *');  //true or false

How does it work

The above code uses the date format specifiers as follows :
'min' => 'i' ,
'hour' => 'G' ,
'day' => 'j' ,
'mon' => 'n' ,
'week' => 'w'

over the timestamp to extract the minute , hour , day , month and week of a timestamp

Then it checks the cron format by splitting it into parts like 0 , 5 , * , * , * and then tests each part for the corresponding value from timestamp.







Thats all for now.
Let us know if you find any bug in the above function.

Last Updated On : 23rd October 2011

Subscribe to get updates delivered to your inbox

1 Comment + Add Comment

  • Good tutorial

Leave a comment