3

I want to schedule an event that occurs every friday at 11:30 am and I'm not sure about a few things. I'm current scheduling an event daily at 11:30am from the following code:

function my_schedule() {

    $hour = 11;
    $minute = 30;
    $dayofweek = 'today';
    $frequency = 'daily';

    if ( !wp_next_scheduled( 'my_event' ) ) {
        $scheduleTime = strtotime($dayofweek." $hour:$minute am America/Montreal");
        wp_schedule_event($scheduleTime, $frequency, 'my_event' );
    } 
}

My question is, if I change $dayofweek to friday, do I need to change $frequency to weekly since $scheduleTime would always be on Fridays? Does $frequency make a difference anymore if I have $scheduleTime that is set to Friday of each week? How exactly does $frequency affect $scheduleTime for wp_schedule_event()?

3

According to the docs for this function, you can't set up a weekly event by default.

wp_schedule_event(int $timestamp, string $recurrence, string $hook, $args = array() );

The $recurrence value needs to be one of:

  • "hourly"
  • "twicedaily"
  • "daily"

You'll need to test today's date inside your callback function, my_event. Something like:

function my_event() {
  # date('l') returns the formatted full day of the week 
  if ( date ('l') !== 'Friday' ) {
    return;
  }
  # do my_event things!
}

Edit:

If you want to add a weekly cron schedule, you can do it by adding a filter to the cron_schedules filter hook. You can see an example of that here, it would work out to something like this:

function 246184_weekly_cron_schedule( $schedules ) {
    $schedules[ 'weekly' ] = array( 
        'interval' => 60 * 60 * 24 * 7, # 604,800, seconds in a week
        'display' => __( 'Weekly' ) );
    return $schedules;
}
add_filter( 'cron_schedules', '246184_weekly_cron_schedule' );
  • Thanks for the reply, do you know how $frequency affects my schedule if $scheduleTime is on a specific date in the future? If $scheduleTime is 1 year in the future and $frequency is daily, does it mean the my event gets called everyday and scheduled 1 year in the future? – iamarnold Nov 14 '16 at 22:24
  • From the docs, it looks like $scheduleTime is the first time you need the cron job to run. Frequency is how often it is run after $scheduleTime. The examples on the docs page all use time(), since that's just whatever the first time the page would be loaded up. After that it would be $frequency from $scheduleTime. – guiniveretoo Nov 14 '16 at 22:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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