运行多个Wordpress Cron来执行两个函数,以不同的固定间隔更新数据库


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

我在Wordpress中执行了多个cron作业。首先,我想明确我已经搜索了很多这个问题,但没有找到确切的解决方案。所以我在这里张贴。

问题是一个cron正在运行,但另一个从未运行,我已经为第一个cron安排了每三个小时的间隔,但它有时会在一分钟内执行多次,因为这收到了多个邮件。而其他的永远不会执行。

有没有人提供通过Wordpress Cron以不同的固定间隔执行两个函数来更新数据库的解决方案?提前感谢。

 //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;
  }

很可能,在编写代码和测试时间间隔期间,您已经安排了一些其他cron_action_two事件,这些事件将在很久以后的某个时间被调用。您可以使用这里显示的方法之一来检查它。Cron清单应该使所有内容都清楚,并且最有可能解决您的问题。

在你的代码中有一些东西应该被修正,以使它更稳定,避免这样的问题:
  1. 清除插件停用时的预定事件,如下所示:

    register_deactivation_hook( __FILE__, 'my_deactivation');
    function my_deactivation() {
        wp_clear_scheduled_hook('my_hourly_event');
    }
    
  2. 在激活时清除计划钩子(YES: wp_clear_scheduled_hook( 'my_hourly_event' );)而不是检查它是否已经存在(NO: if( ! wp_next_scheduled( 'my_hourly_event' ) ))

祝你好运!