wordpress schedule event not firing in set time

2019-05-07 20:42发布

In WordPress I am creating a plugin where I am sending email to users. For that I am using WordPress cron job. So basically what it will do is just send emails to users in every hour. So my code looks like this

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
}

Here everything looks good but it does not sends the email.

If I make my code like this

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

Then it sends the email. But the problem is here it sends the email on every time the page loads or when user visits the site.

That's why I want to use wp_schedule_event to make email in every hour.

So can someone tell me how to resolve this issue?

Any suggestion or help will be really appreciable.

2条回答
smile是对你的礼貌
2楼-- · 2019-05-07 21:29

If you want to run your cron in every one hour then you need to add below code:

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
}

for more information see link

查看更多
聊天终结者
3楼-- · 2019-05-07 21:37

First of all , 1) You need to setup crontab in your server if you want to work dynamically 2) if you want manually wordpress scheduler will call after the page is run

so,

for the crontab setup below is useful link: crontab

查看更多
登录 后发表回答