Search code examples
wordpresscron

Custom cron job doesn't scheduled in Wordpress


I read several questions here and from Google search results, but I wasn't able to make it work. I have a function I want to run once every day which will fetch data from external source and store it on options page.

add_action( 'wp', 'update_stock_market' );
add_action( 'get_stock_market_daily_data', 'get_stock_market_data', 1, 1 );

function update_stock_market() {
    if ( ! wp_next_scheduled( 'get_stock_market_daily_data' ) ) {
        wp_schedule_event( time(), 'daily', 'get_stock_market_daily_data', array($company) );
    }
}

function get_stock_market_data($company ) {
    //do something here to get $data;
    update_option( 'stock_market_data', $data); 
}

However, no matter what happens, I cannot find the scheduled cron in the wp-options table under the option-name of cron


Solution

  • This code is working for me on a clean instance of WordPress, instead of looking directly in the database have you tried using the plugin WP Crontrol? Alternatively, with debug enabled, try adding a log entry to you update_stock_market function to check that the sechudled event is being called.

    add_action( 'wp', 'update_stock_market' );
    add_action( 'get_stock_market_daily_data', 'get_stock_market_data', 1, 1 );
    
    function update_stock_market() {
        error_log( 'triggered' );
        if ( ! wp_next_scheduled( 'get_stock_market_daily_data' ) ) {
            wp_schedule_event( time(), 'daily', 'get_stock_market_daily_data', array($company) );
        }
    }
    
    function get_stock_market_data($company ) {
        //do something here to get $data;
        update_option( 'stock_market_data', $data); 
    }