0

I am working on a class-based plugin. I need a custom cron job that will be active when the plugin is active and run the plugin function. Now, I am facing an issue where it is not calling the plugin function, but I have checked the cron that has already been created. Below is my code. Let me know what I am missing here. smcp_cron_do_task() is not triggered by the cron job.

Also, I'm testing it in my local Docker system.

class ClassName {

    public function __construct() {
        // Ensure custom cron intervals are registered early
        add_filter( 'cron_schedules', array( $this, 'add_custom_intervals' ) );

        // Hooks
        register_activation_hook( __FILE__, array( $this, 'smcp_cron_activate' ));
        register_deactivation_hook( __FILE__, array( $this, 'smcp_cron_deactivate' ));

        add_action( 'smcp_cron_task_hook', array( $this, 'smcp_cron_do_task' ) );
    }

    // Schedule on activation
    function smcp_cron_activate() {
        if ( ! wp_next_scheduled( 'smcp_cron_task_hook' ) ) {
            wp_schedule_event( time(), 'every_minute', 'smcp_cron_task_hook' );
        }
    }

    // Clear scheduled event on deactivation
    function smcp_cron_deactivate() {
        $timestamp = wp_next_scheduled( 'smcp_cron_task_hook' );
        if ( $timestamp ) {
            wp_unschedule_event( $timestamp, 'smcp_cron_task_hook' );
        }
    }

    function smcp_cron_do_task() {
        // Custom Code
        error_log( 'My custom cron job ran at: ' . current_time('mysql') );
    }

    public function add_custom_intervals( $schedules ) {
        $schedules['every_minute'] = array(
            'interval' => 60,
            'display'  => __( 'Every Minute' ),
        );
        return $schedules;
    }
}

// Initialize plugin
new Site_Monitor();

I want to trigger this smcp_cron_do_task() by the cron job.

2
  • 1
    You can install WP Controll to see if your cron task is actualy registered. I usualy avoid using wordpress cron since its not actual cron i prefer using server cron to run my stuff. Commented Sep 11 at 13:57
  • I tried your code and it works directly. I have My custom cron job ran at ... in log every minute. Commented Sep 12 at 5:02

0

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.