DEV Community

AL EMRAN for WP PluginMaster

Posted on

3 1

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

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay