Setting Up Scheduled Tasks (For Scripts to Run)

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.

Related posts

Leave a Reply

1 comment

  1. 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.