Site icon Freelance Web Developer, Web Designer Mumbai India

Cron Jobs or Scheduled Events in WordPress

In this article I will explain how to use cron jobs in WordPress. Let’s understand a cron job first. Cron jobs are scheduled tasks to be executed in an interval of time. WordPress has its own inbuilt system to manage scheduled tasks.

Scheduled tasks could be anything like checking for updates, sending emails, importing xml or deleting old comments.
As we know WordPress comes with set of handy actions and filter that gives us more control.

WordPress has a function called wp_schedule_event to schedule recurring events. This function schedules a hook that will be executed by WordPress core on the scheduled interval. This action triggers when someone visits the site.

Default recurrences are hourly, daily and twicedaily.

Please check below code.


wp_schedule_event(time(), ‘hourly’, ‘custom_hourly_action’);

Remember “custom_hourly_action” is the action name, not the function. The action should be registered.


add_action(‘custom_hourly_action’, ‘custom_hourly_action_callback’);
function custom_hourly_action_callback() {
//Executed hourly
}

Note: Use the wp_schedule_event function on activation hook, otherwise you will end up with many scheduled events.


register_activation_hook(__FILE__, 'activate_callback');
function 'activate_ callback() {
        if (!wp_next_scheduled(‘custom_hourly_action_callback’)) {
            wp_schedule_event(time(), ‘hourly’, ’custom_hourly_action_callback’);
        }
}
register_deactivation_hook(__FILE__, 'deactivate_callback');
function deactivate_callback() {
wp_clear_scheduled_hook(‘custom_hourly_action_callback’);
}

Please check below code to add more recurrences.


add_filter('cron_schedules', 'cron_schedules_callback’);
function cron_schedules_callback($schedules) {

        $schedules['sh_1_mins'] = array(
            'interval' => 60,
            'display' => __('Every Minute', 'textdomain')
        );

        $schedules['sh_5_mins'] = array(
            'interval' => 300,
            'display' => __('Every 5 Minutes', 'textdomain')
        );

        $schedules['sh_10_mins'] = array(
            'interval' => 600,
            'display' => __('Every 10 Minutes', 'textdomain')
        );

        $schedules['sh_15_mins'] = array(
            'interval' => 900,
            'display' => __('Every 15 Minutes', 'textdomain')
        );

        $schedules['sh_30_mins'] = array(
            'interval' => 1800,
            'display' => __('Every 30 Minutes', 'textdomain')
        );

        return $schedules;
}

Now recurrences can be added using below code


wp_schedule_event(time(), 'sh_15_mins', ‘custom_15min_action’);

To execute the cron manually please check the below URL

https://www.yourdomain.com/wp-cron.php?doing_wp_cron

This should execute the task if the scheduled time has passed.

Hope this helps

Exit mobile version