DEV Community

AL EMRAN for WP PluginMaster

Posted on

1.2 WordPress Smart Coding Tips | Schedule Event / scheduled tasks

Image description

Normally in WordPress plugin development, we declare a scheduled event like the following.

register_activation_hook( __FILE__, 'my_plugin_activation_event' );

function my_plugin_activation_event() {
    if ( ! wp_next_scheduled( 'my_plugin_activation_event' ) ) {
        wp_schedule_event( time(), 'daily', 'my_plugin_activation_event' );
    }
}

register_deactivation_hook( __FILE__, 'my_plugin_deactivation_event' );

function my_plugin_deactivation_event() {
    wp_clear_scheduled_hook( 'my_plugin_deactivation_event' );
}
Enter fullscreen mode Exit fullscreen mode

We use this type of code in many places.

Problem is that - This code is not re-usable.

We can create a class for reuse.

Let's Start

  1. Create a class or global functions file

a. First create a class name Schedule

namespace MyPlugin\Utilities;

class Scheduler {

}
Enter fullscreen mode Exit fullscreen mode

b. Then add a method name add

public static function add( $hook, $callback, $recurrence = 'daily', $start_time = null ) {
        if ( ! wp_next_scheduled( $hook ) ) {
            if(!$start_time) $start_time = time();
            wp_schedule_event( $start_time, $recurrence, $hook );
        }

     add_action( $hook, $callback );
 }
Enter fullscreen mode Exit fullscreen mode

** $hook: hook name for the event.
** $callback: callback function or array for add action of our event hook.
** $recurrence: How often the event should subsequently recur. See wp_get_schedules() for accepted values. Default id 'daily'
** $start_time: event first starting time. You can pass your desired time.

c. Then we need to remove/clean our event.
For that let's create a method for removing events.

  public static function delete($hook){
      wp_clear_scheduled_hook($hook);
  } 
Enter fullscreen mode Exit fullscreen mode

Uses

Schedule::add('my-custom-schedule-event', [$this, 'event_handler']);

Schedule::delete('my-custom-schedule-event');
Enter fullscreen mode Exit fullscreen mode

OR you can create global functions as like previous methods.

AL EMRAN
Github

For Creating Awesome Structured PSR Based Plugin:
PluginMaster, a WordPress plugin development framework

Top comments (0)