Search code examples
wordpresscron

Wordpress - set daily cron event


I added in functions.php this piece of code:

function myprefix_custom_cron_schedule( $schedules ) {
    $schedules['every_day'] = array(
        'interval' => 86400, // Every 24 hours
        'display'  => __( 'Every 24 hours' ),
    );
    return $schedules;
}
add_filter( 'cron_schedules', 'myprefix_custom_cron_schedule' );

//Schedule an action if it's not already scheduled
if ( ! wp_next_scheduled( 'mxpbiz_cron_hook' ) ) {
    wp_schedule_event( time(), 'every_day', 'mxpbiz_cron_hook' );
}

///Hook into that action that'll fire every six hours
 add_action( 'myprefix_cron_hook', 'myprefix_cron_check_expired' );

//create your function, that runs on cron
function myprefix_cron_check_expired() {
    //your function...
    file_put_contents( '/var/log/private/checked.log', print_r("checked cron " . date() . PHP_EOL, true ), FILE_APPEND);
}

then I added in crontab this line to execute already the cron :

5 0 * * * /usr/bin/wget https://example.com/wp-cron.php

but no log has created yet in /var/log/private.. at least when crontab starts in five minutes it should at least create the log I think... Did I missed something to consider/follow maybe? Any direction would be appreciate! Thanks in advance to all!! Cheers!


Solution

  • Debugging WordPress cron code is a notorious pain in the xxx neck.

    WP_Cron, of course, already has a 'daily' interval. You might try troubleshooting your code without adding your duplicate interval.

    You should enable WP_DEBUG and WP_DEBUG_LOG when developing and debugging WP_Cron code. Then you should look at .../wp-content/debug.log to see whether your cron-invoked code hit any errors. It's possible your code has a file-permission problem or something else wrong with it. The debug log usually shows error messages. If you don't enable the debug log the cron code crashes silently if it crashes.

    When the debug log is activated you can use the php error_log() function to output information to the debug log file, like this.

    error_log( 'My cron code ran!' );
    

    You generally don't need an OS cronjob to invoke WordPress's cron subsystem. Very busy sites sometimes set DISABLE_WP_CRON, but unless you have set that up you don't have that particular problem. Your cronjob does no harm.

    Finally, John Blackbourn's WP Crontrol plugin lets you examine cronjobs and run them immediately. It's a great help when trying to debug cron code.

    And of course if you put this code in functions.php you run the risk of it being wiped away at the time of a template update.