Setting Up Scheduled Tasks (For Scripts to Run)

WordPress “cron” jobs are database entries that are run on a set schedule, rather than true Linux cron jobs. While WordPress cron jobs are relatively reliable, they do require someone to hit the site in order to check if they need to run. Meaning, if you have a very low traffic site, you may want to set up an actual cron job to ping your site’s front page to ensure your WordPress cron jobs run on time.

WP crons are set using the wp_schedule_event() function. By default, your options are Hourly, Twice Hourly and Daily. To set up a scheduled event, you create a hook:

function set_up_scheduled_event() {
    if ( !wp_next_scheduled( 'Send_Report' ) ) {
        wp_schedule_event( time(), 'daily', 'Send_Report');
    }
}
add_action('wp', 'set_up_scheduled_event');

This will create a hook for you called ‘Send_Report’ that will run once a day, starting 24 hours from the time this script runs. It also ensures that it doesn’t overwrite itself.

Next, you need to hook what you want to do onto the new hook you created.

add_action('Send_Report', 'actually_send_report');
function actually_send_report {
// do something cool here, like generate a report and email it
}

If hourly, twice hourly or daily aren’t the right options for you, you can create new time intervals through the cron_schedules filter.

add_filter('cron_schedules', 'add_weekly_and_monthly_cron');
function add_weekly_and_monthly_cron( $schedules )
    {
        if(!array_key_exists('weekly',$schedules))
        {
            $schedules['weekly'] = array(
                'interval' => 604800,
                'display' => __( 'Once Weekly' )
            );
        }
        if(!array_key_exists('monthly',$schedules))
        {
            $schedules['monthly'] = array(
                'interval' => 2592000,
                'display' => __( 'Once Monthly' )
            );
        }
        return $schedules;
    }

The interval in these cases is the number of seconds between the cron jobs.