1

I am writing a script to add a named Cron job that updates a single user, that runs every 5 minutes or so.

My problem is that the job runs for every user over and over again every second or so. Here is the code that I have placed inside my functions.php file.

This is my first foray into the WP Cron functionality with WordPress and would like to know if I set up the jobs correctly.

function so_custom_cron_schedule( $schedules ) {
    $schedules['every_5_minutes'] = array(
        'interval' => 300,
        'display'  => __( 'Every 5 minutes' ),
    );
    return $schedules;
}
add_filter( 'cron_schedules', 'so_custom_cron_schedule' );

function update_social_user($user_id){
  $user = get_userdata($user_id);
  if(!$user){
    return;
  }
  var_error_log('running for '.$user_id);
}

function assign_cron(){
  $users = get_users([ 'role__in' => [ 'administrator', 'seller'] ]);
  $args = array(false);
  foreach($users as $user){
    $hook_name = 'update_fb_'.$user->ID;
    add_action($hook_name,'update_social_user');
    if(!wp_next_scheduled($hook_name,$args)){
      wp_schedule_event(time(),'every_5_minutes',$hook_name,array($user->ID));
    }else{
      var_error_log('Already set');
    }
  }
}

assign_cron();
0

I usually define a IF state and use wp_clear_scheduled_hook function. See example:

if (get_option('atenasupervisor_scheduler') <> 'Stop') {
   echo 'Active ('. get_option('atenasupervisor_scheduler').')</strong></div>';
} else {
    wp_clear_scheduled_hook( 'atenasupervisor_my_email' );
    echo 'Not active ('. get_option('atenasupervisor_scheduler').')</strong></div>';
}
``
| improve this answer | |

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.