DEV Community

Muhammad Shoaib
Muhammad Shoaib

Posted on

Create Cron Jobs In Wordpress

A cron job allows you to automatically set a function to run at a set time or interval. Wordpress comes with an in-built function wp_schedule_event(). Wordpress Schedule Event.

The function wp_schedule_event() allows you schedule a hook to run an action to schedule a function to run at a set interval

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

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

//Hook into that action that'll fire every six hours
add_action( 'myprefix_cron_hook', 'myprefix_cron_function' );
//create your function, that runs on cron
function myprefix_cron_function() {
    //your function...
}

This script will run every six hours which isn't a big hit to the server as all it will do is check the current hours before deciding to run the script, but now we can have a script that runs every six hours. If you want to run this script at a certain time then you need to change this wp-cron to run hourly and check both the day and the time is what you want it to be.

Top comments (0)