WordPress schedule event not firing in set time

In WordPress, I am creating a plugin where I am sending emails to users. For that, I am using WordPress cron job. So basically what it will do is just send emails to users 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 send the email.

Read More

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 the user visits the site.

That’s why I want to use wp_schedule_event to make emails every hour.

So can someone tell me how to resolve this issue?

Any suggestions or help will be really appreciated.

Related posts

2 comments

  1. 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

  2. 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

Comments are closed.