This handler cron is intended to be called every 5 mins and will run 5 min tasks and 1 hour tasks, using a timestamp stored for each. If it hasn’t been called every 5 mins it will loop the 5 min tasks to catch up


  //----- GET CRON LAST RUN TIME STAMPS -----
  $CronLastRunDateTime = get_site_option('MYPLUGINNAME_CronLastRunDateTime');   //Already stored as strtotime()
  $TheDateTimeNow = strtotime(date("Y-m-d H:i:s"));
                              
  if ($CronLastRunDateTime === False)
    $CronLastRunSecondsAgo = (60 * 60);     //Default to 1 hour ago
  else
    $CronLastRunSecondsAgo = $TheDateTimeNow - $CronLastRunDateTime;
  
  if ($CronLastRunSecondsAgo < 0)
    $CronLastRunSecondsAgo = (5*60);    //Something bad has happened, set to run now once
  
  $CronLastRunHour = get_site_option('MYPLUGINNAME_CronLastRunHour', -1);
  $TheHourNow = intval(date("H"));
  
  
  //We want to ensure that we run our every 5 mins tasks multiple times if its taken longer than 5 mins to get here, e.g. on a site where cron isn't happening every 5 mins due to
  //low visitor numbers and no dedicated cron event setup.
  if ($CronLastRunSecondsAgo > (60 * 60))   //Limit to max 1 hour, if its more than this then discard additional 5 min events as we don't want to go crazy with this feature
    $CronLastRunSecondsAgo = (60 * 60);
  
  while ($CronLastRunSecondsAgo >= ((5*60)-10) )      //Give a little bit of error margin, 10 secs
  {
    $CronLastRunSecondsAgo -= (5 * 60);
    //--------------------------------------
    //--------------------------------------
    //----- DO ONCE EVERY 5 MINS TASKS -----
    //--------------------------------------
    //--------------------------------------
    
    
    
    
    
    //All done - Store the time stamp
    update_option('MYPLUGINNAME_CronLastRunDateTime', $TheDateTimeNow, True);
  } //while ($CronLastRunSecondsAgo >= ((5*60)-10) )
  

  if ($CronLastRunHour != $TheHourNow)
  {
    //----------------------------------
    //----------------------------------
    //----- DO ONCE PER HOUR TASKS -----
    //----------------------------------
    //----------------------------------
  

    
    
    //All don - Store the hour
    update_option('MYPLUGINNAME_CronLastRunHour', $TheHourNow, True);
  } //if ($CronLastRunHour != $TheHourNow)
Feel free to comment if you can add help to this page or point out issues and solutions you have found. I do not provide support on this site, if you need help with a problem head over to stack overflow.

Comments

Your email address will not be published.