Cron Jobs and WordPress

, ,
function some_plugin_activation() {
    if (!wp_next_scheduled( 'some_plugin_check_cron_event' )) {
    	some_plugin_schedule_event();
    } else {
    	some_plugin_deactivation();
    	some_plugin_schedule_event();
    }
}

function some_plugin_deactivation() {
    if ( wp_next_scheduled ( 'some_plugin_check_cron_event' )) {
    	wp_clear_scheduled_hook( 'some_plugin_check_cron_event' );
    }
}
// I like scheduling it this way so that it fires in my own time frame but you can also use wp_schedule_event to repeat in a specified timeframe.
function some_plugin_schedule_event() {
    $nextMonday = strtotime('next monday');
    wp_schedule_single_event($nextMonday, 'some_plugin_check_cron_event');
}

add_action('some_plugin_check_cron_event','some_plugin_check_cron_fire');
function some_plugin_check_cron_fire() {
    // Do what needs to be done in the cron 

    some_plugin_activation(); // this reschedules the cron to run again.
}

 

Occasionally you find the need to have scheduled tasks run in WordPress. Ideally this should be done using WordPress Cron which allows you to tie in with visits to the website as to things being run periodically.

The main commands that you will be needing are the following commands:

wp_schedule_event( int $timestamp, string $recurrence, string $hook, array $args = array() ). This can be used to create an event that will be repeated with time. Timestamp can be time() plus any number of seconds if you choose to schedule it in the future.  For recurrence the main string values that can be used are: ‘hourly’, ‘twicedaily’, ‘daily’, and ‘weekly’.  You can also use wp_get_schedules() to get all the schedules that have been created in your wordpress system, or you can create your own by adding a filter to the cron_schedules hook. The hook should be the name of the add_action you have created that would then fire the function you also assign.

wp_schedule_single_event( int $timestamp, string $hook, array $args = array() ) can be used to schedule an event to fire once.

wp_clear_scheduled_hook( string $hook ) can be used to clear any scheduled cron jobs from the system.

wp_next_scheduled( string $hook) can be used to see the next time an event is set to be run. If it returns an empty string then it isn't currently set to run.  So by checking the result for an empty string you can reschedule the cron job to run if it should be.

These are the main functions that can be used within a plugin to setup a cron job to fire. Allowing you to have a setting in your plugin as to whether the cron job should be on, check to see if it is on, if it isn't then schedule it to be put into the cron, and then finally turn it off.

 

Skills

Posted on

September 22, 2020

Submit a Comment

Your email address will not be published. Required fields are marked *