Run more than one WordPress Cron for executing two functions for updating database at different fixed intervals

I have executed multiple cron jobs in WordPress. First of all i want to clear i have searched lot for this problem but not found exact solution. So i have posted here.

Problem is that one cron is running but another is never running and i have scheduled a interval of every three hour for first cron but it sometime execute multiple time within a minute for this got multiple mail. And other never execute.

Read More

Anyone provide solution for executing two functions for updating database at different fixed intervals through WordPress Cron. Many thanks in advance.

 //The activation hooks is executed when the plugin is activated
 register_activation_hook(__FILE__, 'activate_one');
 register_activation_hook(__FILE__, 'activate_two');
 //Filter for Adding multiple intervals
 add_filter( 'cron_schedules', 'intervals_schedule' );

 function intervals_schedule($schedules) {
     $schedules['threehour'] = array(
        'interval' => 10800, // Every 3 hours
        'display'  => __( 'Every 3 hours' )
     );
     $schedules['onehour'] = array(
         'interval' => 3600, // Every 1 hour
         'display'  => __( 'Every 1 hour' )
     );

     return $schedules;
  }

  //Schedule a first action if it's not already scheduled
  function activate_one() {
      if (!wp_next_scheduled('cron_action_one')) {
          wp_schedule_event( time(), 'threehour', 'cron_action_one');
      }
  }

  //Hook into that action that'll fire threehour
  add_action('cron_action_one', 'execute_one');

  function execute_one()
  {
      //Do something or update in database;
  }

  //Schedule a second action if it's not already scheduled
  function activate_two() {
      if (!wp_next_scheduled('cron_action_two')) {
          wp_schedule_event(time(), 'onehour', 'cron_action_two');
      }
  }

  //Hook into that action that'll fire onehour
  add_action('cron_action_two', 'execute_two');

  function execute_two()
  {
      //Do something or update in database;
  }

Related posts

1 comment

  1. Most probably, during writing of your code and testing time intervals, you already scheduled some other cron_action_two event, that will be called at some time much later. You can check it using one of the methods shown here. Cron listing should make everyting clear, and most likely will resolve your issue.

    There are some things that should be fixed in your code to make it more stable and avoid such issues:

    1. Clear scheduled events on plugin deactivation something like this:

      register_deactivation_hook( __FILE__, 'my_deactivation');
      function my_deactivation() {
          wp_clear_scheduled_hook('my_hourly_event');
      }
      
    2. Clear scheduled hook on activation (YES: wp_clear_scheduled_hook( 'my_hourly_event' );) instead of checking if it already exists (NO: if( ! wp_next_scheduled( 'my_hourly_event' ) ))

    Good Luck!

Comments are closed.