WordPress计划事件未在设定时间内启动


WordPress schedule event not firing in set time

在WordPress中,我正在创建一个插件,用于向用户发送电子邮件。为此,我使用WordPress cron作业。所以基本上,它只会每小时向用户发送电子邮件。所以我的代码看起来像这个

public function __construct() {
    add_action('init', array( $this, 'send_emails_to_users') );  
    add_action('cliv_recurring_cron_job', array( $this, 'send_email') );
}
public function send_emails_to_users() {
  if(!wp_next_scheduled('cliv_recurring_cron_job')) {
          wp_schedule_event (time(), 'hourly', 'cliv_recurring_cron_job');
    }
}
public function send_email() {
    //send email code goes here
}

这里的一切看起来都很好,但它没有发送电子邮件。

如果我把我的代码做成这样的

public function __construct() {
    add_action('head', array( $this, 'send_email') );  
}

然后它发送电子邮件。但问题是,每当页面加载或用户访问网站时,它都会发送电子邮件。

这就是为什么我想用wp_schedule_event每小时发一封电子邮件。

那么有人能告诉我如何解决这个问题吗?

任何建议或帮助都将不胜感激。

首先,1) 如果希望动态工作,则需要在服务器中设置crontab2) 如果你想手动wordpress调度程序将在页面运行后调用

所以,

对于crontab设置,以下是有用的链接:crontab

如果你想每一小时运行一次你的cron,那么你需要添加以下代码:

public function __construct() {
    // Call function for cron
    add_action('init', array( $this, 'send_emails_to_users') );
}
public function send_emails_to_users() {
    if(!wp_next_scheduled('cliv_recurring_cron_job')) {
        // Add "cliv_recurring_cron_job" action so it fire every hour
        wp_schedule_event(time(), 'hourly', 'cliv_recurring_cron_job');
    }
}
add_action('cliv_recurring_cron_job', array( $this, 'send_email') );
public function send_email() {
    //send email code goes here
}

有关更多信息,请参阅链接