shshanker
10/7/2015 - 4:24 AM

//Create Cron Jobs In WordPress

//Create Cron Jobs In WordPress

<?php



//Schedule An Hourly Event In Plugin
register_activation_hook(__FILE__, 'my_activation');
add_action('my_hourly_event', 'do_this_hourly');

function my_activation() {
	wp_schedule_event( current_time( 'timestamp' ), 'hourly', 'my_hourly_event');
}

function do_this_hourly() {
	// do something every hour
}

register_deactivation_hook(__FILE__, 'my_deactivation');

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





//Schedule hourly Event In Functions.php

add_action('my_hourly_event', 'do_this_hourly');

function my_activation() {
	if ( !wp_next_scheduled( 'my_hourly_event' ) ) {
		wp_schedule_event( current_time( 'timestamp' ), 'hourly', 'my_hourly_event');
	}
}
add_action('wp', 'my_activation');

function do_this_hourly() {
	// do something every hour
}



//Add New Cron Intervals
function add_new_intervals($schedules) 
{
	// add weekly and monthly intervals
	$schedules['weekly'] = array(
		'interval' => 604800,
		'display' => __('Once Weekly')
	);

	$schedules['monthly'] = array(
		'interval' => 2635200,
		'display' => __('Once a month')
	);

	return $schedules;
}
add_filter( 'cron_schedules', 'add_new_intervals');




//Cron At Certain Day's And Time

wp_schedule_event( current_time( 'timestamp' ), 'weekly', 'my_weekly_event');
add_action('new_daily_event', 'monday_event');

function monday_event_activation() 
{
    if ( !wp_next_scheduled( 'new_daily_event' ) ) {
        wp_schedule_event( current_time( 'timestamp' ), 'daily', 'new_daily_event');
    }
}
add_action('wp', 'monday_event_activation');

function monday_event()
{
    // Get the current date time
    $dateTime = new DateTime();

    // Check that the day is Monday
    if($dateTime->format('N') == 1)
    {
        // run script
    }
}



?>