WordPress’ pseudo cron

It just doesn’t work and I have no idea what’s wrong. Maybe someone can help me.
Here is my code:

add_action('kawabunga',function(){
    echo '<h1>KAWABUNGA!!!!1</h1>';
});


if (!wp_next_scheduled('kawabunga')) {
    wp_schedule_single_event(time()+120, 'kawabunga');
}

Then I used this code to look at what’s happening with a task:

Read More
echo 'scheduled = ' . wp_next_scheduled('kawabunga');
echo '<br>time = ' . time();

And it acted as I expected: first displayed both timestamps and in 2 minutes only the second one, because an action was executed and it wasn’t scheduled anymore so it returned “false”, not a timestamp.
But my function wasn’t actually executed, it didn’t print <h1>KAWABUNGA!!!!1</h1> and my IDE didn’t stop on the breakpoint.

I also tested an action in other part of the site: do_action('kawabunga'); and it worked just fine. It doesn’t work only in cron.

Any ideas?

Related posts

Leave a Reply

2 comments

  1. Aurimas is right, you need to define a function that can be called in a later request. So using an anonymous function will not work here.

    I believe that cron processing is triggered after page output, so as not to slow down the user’s experience. Outputting an won’t have any effect. You would be better to test with a call to mail() or wp_mail() (or write to a file if mail doesn’t work on your system).

    With those two corrections, your code looks good.

  2. Try calling wp_cron() after those lines:

    add_action('kawabunga', function(){
        echo '<h1>KAWABUNGA!!!!1</h1>';
    });
    
    if (!wp_next_scheduled('kawabunga')) {
        wp_schedule_single_event(time()+120, 'kawabunga');
    }
    
    wp_cron();