How to Use WP Cron

Scheduling an event in WordPress is very common. This functionality is commonly known as CRON. Here are the steps on how to can create CRON tasks.

Step 1: Determine the desired recurrence

There are three predefined recurrences defined by WordPress, namely: daily, twicedaily, & hourly.

If you want to define your own recurrence, you can do so. Below is an example of adding a recurrence every2mins which obviously means that the recurrence every 2 minutes:

add_filter('cron_schedules',  'add_cron_recurrence');

function add_cron_recurrence($schedules) {
        if(!isset($schedules[$this->_name])){
            $schedules['every2mins'] = array(
                'interval' => 2 * 60, //120 seconds
                'display' => __('Run every 2 mins');
        }

        return $schedules;        
}

Change values as desired.

Step 2: Register your cron task(s)

Here is a simple way to implement a cron or registering an event which will be executed every hour:

register_activation_hook(__FILE__, 'my_activation');

function my_activation() {
    if (! wp_next_scheduled ('my_hourly_event')) {
        wp_schedule_event(time(), 'hourly', 'my_hourly_event');
    }
}  

add_action('my_hourly_event', 'do_this_hourly');

function do_this_hourly() {
    // do something every hour
}

register_deactivation_hook($file, 'my_deactivation');

function my_deactivation() {
	wp_clear_scheduled_hook('my_hourly_event');
}

To change the recurrence, run it every 2 minutes, for example, we can use the recurrence above. In the function my_activation, look for the ff. line:

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

Change hourly to every2mins, or the name of the recurrence you defined.


You can create as many custom recurrence and events as needed. It’s just a matter of changing values. To make it easier for you, I created a class which will allow you to register events into the WordPress Cron without the need to do the above steps.

Step 1: Copy the Cron Class from WDT-Framework

Step 2: Include/Require the class in your plugin.

Step 3: On the main file of your plugin, add the ff. codes:

new \wdtf\WPCronEvent(__FILE__, 60, 'executeThisFunc');

60 is the interval of the recurrence (in seconds). You can also use ‘daily’, ‘twicedaily’, or ‘hourly’
executeThisFunc is the name of the function that will get executed and you can rename it.

Step 4: Define your function.


Don’t forget to reactivate your plugin to make the cron work.


 

Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedInPrint this pageEmail this to someone

Leave a Reply

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