【问题标题】:Run a function every day in specific time [duplicate]每天在特定时间运行一个函数[重复]
【发布时间】:2020-01-13 23:22:28
【问题描述】:

我有一个从 API 获取数据的函数。 我想在每天的特定时间运行这个功能。我使用下面的代码来实现这一点,但是每分钟运行一次。我在 5 分钟间隔内使用此代码进行预定测试。我的 API 代码太长了。我在那里只使用测试目的示例代码。

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');
}

【问题讨论】:

    标签: php wordpress function api events


    【解决方案1】:

    您可以使用 crontab 来执行此操作,例如每天 06:02。

    crontab -e 然后添加6 2 * * * curl http://api

    【讨论】:

    • 如果有什么方法可以通过功能实现这一点? functioncorntab -e 之间的最佳解决方案是什么
    • 函数也由 crontab 调度。
    • 你能举个例子吗?到现在我还没用过crontab -e
    • 执行时会进入contab编辑模式,然后添加该行。
    【解决方案2】:

    wp_schedule_event 函数中的用法如下所示:

    使用 strtotime() 函数,以便您可以指定一天中的时间 - 它将使用今天的日期和您指定的时间。

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

    编辑

    你必须在预定后设置下一个预定时间

    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');
    }
    

    【讨论】:

      猜你喜欢
      • 2013-07-09
      • 2019-05-23
      • 1970-01-01
      • 2020-11-23
      • 2021-04-05
      • 2019-04-01
      • 2020-08-28
      • 2021-01-04
      • 2013-04-18
      相关资源
      最近更新 更多