Schedule cron event from widget

Can I use wp_schedule_event() to set up a cron job from within a widget?

I tried, but I can’t make it work, The problem seems to be the $hook parameter. The function I’m trying to hook is located within the widget class so my guess is that WP can’t find it.

Read More

neither of these work:

wp_schedule_event(time(), 'daily', 'my_widget_cron');
wp_schedule_event(time(), 'daily', array(&$this, 'my_widget_cron'));

any ideas?

Related posts

Leave a Reply

1 comment

  1. wp_schedule_event takes a hook as parameter, not a function. Try:

    wp_schedule_event(time(), 'daily', 'my_daily_event');
    
    add_action('my_daily_event', array(&$this, 'my_widget_cron'));
    
    if ( !wp_next_scheduled( 'my_daily_event' ) ) {
        wp_schedule_event(time(), 'hourly', 'my_daily_event')
    }
    

    If you remove the widget from the sidebar, the cron will still continue to run.
    You can run the following code (outside of the widget class) to clear it:

    if ( !is_active_widget('your_widget_callback_function') && wp_next_scheduled( 'my_daily_event' ) ) {
        wp_clear_scheduled_hook('my_daily_event');
    }