0

I have a function which has got data from the API. I want to run this function in every day at a specific time. I have used below code for achieving this, but the blow of run every min. I am using this code on the 5min interval for scheduled tests. My API code is, too much long. I am using just test purpose example code there.

register_activation_hook(__FILE__, 'my_activation');
add_action( 'wp', 'my_activation' );

function my_activation() {
    if (! wp_next_scheduled ( 'my_hourly_event' )) {
    wp_schedule_event(time(), 'hourly', 'my_hourly_event');
    }
}

add_action('my_hourly_event', 'do_this_hourly');

function do_this_hourly() {
    // do something every hour
    $t          = time();
    $user_login = 'test-'.$t;
    $user_email = 'test-'.$t.'@yahoo.com';
    $user_pass  = '123456';

    $userdata = compact( 'user_login', 'user_email', 'user_pass' );
    $user_id = wp_insert_user( $userdata ) ;

    // On success.
    if ( ! is_wp_error( $user_id ) ) {
        echo "User created : ". $user_id;
    }else{
        echo "<h1>User already exsist</h1>";

    }
}

register_deactivation_hook(__FILE__, 'my_deactivation');

function my_deactivation() {
    wp_clear_scheduled_hook('my_hourly_event');
}
Kane
  • 605
  • 2
  • 8
  • 22

2 Answers2

2

You can use crontab to do it, for example 06:02 each day.

crontab -e then add 6 2 * * * curl http://api

LF00
  • 27,015
  • 29
  • 156
  • 295
1

Usage in the wp_schedule_event function would look like this:

use strtotime() function so you can specify the time of day - it will use today's date with the time that you specify.

wp_schedule_event( strtotime('16:20:00'), 'daily', 'my_daily_event' );

Edit

and you have to set next schedule time after scheduled

if (!wp_next_scheduled('my_daily_event')) {
    $time = strtotime('today'); //returns today midnight
    $time = $time + 72000; //add an offset for the time of day you want, keeping in mind this is in GMT.
    // Ex: $time = strtotime("+1 day");
    wp_schedule_event($time, 'daily', 'my_daily_event');
}
Manian Rezaee
  • 1,012
  • 12
  • 26