Cron jobs in a class

I was working with wp_cron last week in a plugin and we have a fight and are no longer on speaking terms, but for reference this is what I do;

1) – set the scheduled cron event on register_activation_hook
2) – remove the scheduled cron event on register_deactivation_hook

If you are concerned that your scheduled cron event might get wiped from the database then you can add routine as you already have to check for your cron events next scheduled timestamp;

if (!wp_next_scheduled('dailyExport')) { 
    //schedule event 
    wp_schedule_event( time(), 'daily', 'dailyExport' );
}

My example class;

register_activation_hook(__FILE__, array( 'Killa', 'activated' ) );
register_deactivation_hook( __FILE__, array( 'Killa', 'deactivated' ) );

add_action('plugins_loaded', array ( Killa::get_instance(), 'plugin_setup' ) );

class Killa
{
    protected static $instance = NULL;
    public static function get_instance()
    {
        if ( null === self::$instance )
        {
            self::$instance = new self;
            self::load_files();
        }
        return self::$instance; 
    }

    public function plugin_setup()
    {
        add_action('my_cron_event', array($this, 'my_callback_function'));     
    }

    public function __construct()
    {
        //empty
    } 

    public static function activated() 
    {
        wp_schedule_event( time(), 'hourly', 'my_cron_event');
    }

    public static function deactivated() 
    {
        wp_clear_scheduled_hook( 'my_cron_event' );
    }

    public function my_callback_function()
    {
       //do your thing here... such as generate JSON
    }
}

Bottom line is that it’s perfectly OK to define your register activation/deactivation hooks as static functions and more appropriately so when working in a singleton type pattern or when your activated()/deactivated() functions might exist within another class call by your controller.

It’s also acceptable to have your registration hooks within the constructor too, depending upon your class structure.

Leave a Comment