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:
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:
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.