WordPress Cron Job

What is the reason for below :

wp_unschedule_event

Read More

and

add_action ‘wp’

Have a look please on this code , it is a simple cron job plugin that insert data into db every 1 min

<?php
/*
Plugin Name: Cron Job
Description: My Cron Job
Version: 4.0
Author: Bassem
License: GPL
*/
?>

<?php
//Add Interval [ Minute ] 
function cron_add_minute($schedules) 
{
    // Adds once every minute to the existing schedules.
    $schedules['EveryOneMinute'] = array('interval' => 60,'display' =>( 'insert record into DB' ) );
    return $schedules;
}
add_filter( 'cron_schedules', 'cron_add_minute' );
//==================================
//Create a new CronJob
function cronStartActive() 
{
    if( !wp_next_scheduled( 'mycron' ) )
    {  
         wp_schedule_event(time(), 'EveryOneMinute', 'mycron' );  
    }
}
add_action('wp', 'cronStartActive');
//==================================

function cronStartDeactive(){   
    $timestamp = wp_next_scheduled ('mycron');
    wp_unschedule_event ($timestamp, 'mycron');
} 
register_deactivation_hook (__FILE__, 'cronStartDeactive');

//================================================================
function myWpTask()
{
    global $wpdb;
    $date=date('Y-m-d H:i:s');
    $query="insert into _testcron(added_on) values('$date')";
    $insert=$wpdb->query($query);
}
add_action ('mycron', 'myWpTask'); 
?>

the code works fine , I follow tutorial in this link but i need to understand some points :

  1. what is the reason for cronStartDeactive() function , when i remove it , the cron job still work , so what is the aim of using it
  2. the same goes for add_action(‘wp’, ‘cronStartActive’); , when i comment it the cron still works.

Related posts

Leave a Reply