Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I am going to make a script that requires a scheduled run time. What is the best way to do this in Wordpress? Or maybe this can be done through some PHP method? I'm having a hard time finding even a clear place to start on this.

Forgive the vague tag. "chron, scheduled" and other helpful tags were rejected by system and couldn't submit.

share|improve this question

1 Answer 1

up vote 1 down vote accepted

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.

share|improve this answer
    
This is plenty sufficient. Thank you very much, and the detailed explanation. –  user1915665 Apr 13 '13 at 0:05

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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