The goal

I want to use wp_schedule_single_event( ) to execute a single event that sends me an e-mail 8 minutes after the user submits a form.

The issue

The following code is in my functions.php:

function nkapi_send_to_system( $args ) {
  wp_mail( 'xxx', 'xxx', $args );
}

add_action( 'nkapi_send', 'nkapi_send_to_system' );

function schedule_event( $id ) {
  wp_schedule_single_event( current_time( 'timestamp' ) + 480, 'nkapi_send', array( $id ) );
}

And the following code is used to call schedule-event:

schedule_event( $_SESSION['insert_id'] ); // the $_SESSION var contains an INT

After waiting some more than 8 minutes there wasn’t an e-mail in my inbox.

What I tried

With the plugin Core Control it’s possible to see wich cron jobs are scheduled.

Core Control screen

After a couple of changes I managed to get them quite correct, and better, when I hit “Run Now”, I actually get an e-mail in my inbox.

But why the cron’s don’t execute when I visit my site after 8 minutes.
What possibly is wrong with this code? I have to say that this is my first time using WP Cron.

I tried more

After the comment of vancoder id decided to test if the code works if I put the following code directly in the functions.php:

function schedule_event( $id ) {
  wp_schedule_single_event( time(), 'nkapi_send', array( $id ) );
}

if ( isset( $_SESSION['insert_id'] ) ) {
  if ( ! array_key_exists( 'insert_scheduled', $_SESSION ) || $_SESSION['insert_scheduled'] != $_SESSION['insert_id'] ) {
    schedule_event( $_SESSION['insert_id'] );
    $_SESSION['insert_scheduled'] = $_SESSION['insert_id'];
  }
}

The downside of this code is, the user has to go to another page before this code is executed. But on the other side, this doesn’t work either so that wouldn’t be my first issue…

6

First can you please confirm that you don’t have any caching plugins enabled? Caching plugins can interfere with cron jobs because your visitors are not served a live page but a cached version of your page.

If you have a caching plugin enabled, you can choose one of your pages, add an exclussion to your caching plugin’s settings for that page so that it is never cached.

Then you’ll have to manually create a cron job (using cpanel if you’re on a shared hosting environment or from the terminal if it’s a VPS/dedicated server) that will visit that page every few minutes.

I hope that helps!

Leave a Reply

Your email address will not be published. Required fields are marked *