1

I want to add to wp_schedule_event when the plugin is activated, the code I need does run on the hour, but seems to run twice and I can't work out why, I expect I am doing something incorrect with the way I am calling this.

This is what I have

plugin.php file

namespace GrantName {
  if ( ! defined('ABSPATH' ) ){
    die();
  }
  class Plugin {
    private static $instance = null;
    private static $plugin_dir;  

    private function __construct(){
      $autoloader_path = self::getPluginFilePath("/autoloader.php");
      require_once($autoloader_path);
      Autoloader::register();

      new AdminSupport();
      $adminClass = new AdminSupport(); 

      // These are the de/activation hooks.
      register_activation_hook(__FILE__, array($adminClass, 'my_activation'));
      register_deactivation_hook( __FILE__, array($adminClass,'my_deactivation' ));

    }

AdminSupport.php

namespace GrantName;
class AdminSupport {

  public function onInitialize(){
    add_action('my_hourly_event', array($this, 'do_this_hourly' ));
  }

  public function my_activation() {
    wp_schedule_event( time(), 'hourly', 'my_hourly_event' );
  }

  public function do_this_hourly() {
    // do something every hour
    $this->assessplugins();
  }

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

  public function assessplugins(){
    //Does some things
  }
};

It seems that the scheduled tasks run twice, one after the other. I installed a plugin to show the tasks and I see that the job has two actions (do_this_hourly() twice).

Can anyone see what I am doing wrong?

Edit: I think the issue is that init is called multiple times, so my hooks are added more than once.

1 Answer 1

0

It looks like you know what's going on - here's a way to avoid running the activation method more than once:

class AdminSupport {
    protected static $activated = false;

    public function onInitialize(){
        add_action('my_hourly_event', array($this, 'do_this_hourly' ));
    }

    public function my_activation() {
        if ( self::$activated ) {
            return;
        }

        wp_schedule_event( time(), 'hourly', 'my_hourly_event' );
        self::$activated = true;
    }

    public function do_this_hourly() {
        // do something every hour
        $this->assessplugins();
    }

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

    public function assessplugins(){
        //Does some things
    }
}
1
  • I actually add the self::$activated = true; part into the onInitialize function, like this: if ( !self::$activated ) { //do the things that should happen once; self::$activated = true;} - thanks for the help
    – mozman2
    May 2, 2017 at 14:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.