Recurring scheduled task help

I’m trying to set up a scheduled task in my WordPress installation which will (eventually) run a script to send an email once a day with a load of data in.

However I can’t seem to get a scheduled task to fire at all. I am testing it with a 2 minute interval to see if I can get it working. What I have so far is below, and is at the bottom of my functions.php file. Any idea where I’m going wrong?

Read More
add_filter('cron_schedules','my_cron_definer');
function my_cron_definer($schedules){
    $schedules['twomin'] = array(
        'interval'=> 120,
        'display'=>  __('Once Every 2 Minutes')
    );
    return $schedules;
}

add_action('my_periodic_action','my_periodic_function');
function my_periodic_function(){
    mail('email@address.co.uk','Test!', 'Test Message');
}
wp_schedule_event(time(), 'twomin', 'my_periodic_action');

I’m aware my WordPress site needs to be getting it’s pages visited for the function to run, so I have been clicking around on the site hoping to trigger my function but no luck!

Note: I have swapped my real email address out!

Related posts

Leave a Reply

1 comment

  1. You have to schedule your event in a hook, for example in after_setup_theme or wp actions:

    add_filter('cron_schedules','my_cron_definer');
    function my_cron_definer($schedules){
        $schedules['twomin'] = array(
            'interval'=> 120,
            'display'=>  __('Once Every 2 Minutes')
        );
        return $schedules;
    }
    
    add_action('my_periodic_action','my_periodic_function');
    function my_periodic_function(){
        mail('email@address.co.uk','Test!', 'Test Message');
    }
    
    add_action( 'wp', 'wpse8170_setup_events' );
    // or add_action( 'after_setup_theme', 'wpse8170_setup_events' );
    function wpse8170_setup_events() {
        if ( !wp_next_scheduled( 'my_periodic_action' ) ) {
            wp_schedule_event(time(), 'twomin', 'my_periodic_action');
        }
    }