admin管理员组

文章数量:1418590

I'm trying to add a cron job to run file daily at 7pm.

How can i add the file run command and specify to run it at 7pm ?

// Scheduled Action Hook
function run_my_script( ) {
// run my file : mysite/cron.php
}
// Schedule Cron Job Event
function USERS_MONITORING() {
if ( ! wp_next_scheduled( 'USERS_MONITORING' ) ) {
    wp_schedule_event( time(), 'daily', 'USERS_MONITORING' );
}
}
add_action( 'wp', 'USERS_MONITORING' );

I don't know if there is a better solution.

I'm trying to add a cron job to run file daily at 7pm.

How can i add the file run command and specify to run it at 7pm ?

// Scheduled Action Hook
function run_my_script( ) {
// run my file : mysite/cron.php
}
// Schedule Cron Job Event
function USERS_MONITORING() {
if ( ! wp_next_scheduled( 'USERS_MONITORING' ) ) {
    wp_schedule_event( time(), 'daily', 'USERS_MONITORING' );
}
}
add_action( 'wp', 'USERS_MONITORING' );

I don't know if there is a better solution.

Share Improve this question edited Aug 9, 2017 at 10:13 octavelhiver asked Aug 9, 2017 at 9:17 octavelhiveroctavelhiver 231 silver badge4 bronze badges 4
  • What file are you trying to run? If it's just a generic PHP file, I'd suggest using the native cron of your server. – Jacob Peattie Commented Aug 9, 2017 at 9:21
  • A php file on my server ( question updated ). The native cron of my server does'nt work. – octavelhiver Commented Aug 9, 2017 at 9:47
  • 1 WP Cron doesn't run files, it fires actions/hooks, the code in your question should generate a fatal error as you've defined a function with the same name twice, and function names should be unique. I would also be careful having standalone files like cron.php, for security reasons. I could hit that file repeatedly to cause a denial of service attack via resource exhaustion – Tom J Nowell Commented Aug 9, 2017 at 9:56
  • Ok noted. Any suggestions to do the job ? – octavelhiver Commented Aug 9, 2017 at 9:58
Add a comment  | 

1 Answer 1

Reset to default 2

You can include the PHP file and do the tasks, if WP-cron is your only option.

// Scheduled Action Hook
function run_my_script( ) {
    require_once('related/path/to/php/file.php');
}
// Schedule Cron Job Event
function USERS_MONITORING() {
    if ( ! wp_next_scheduled( 'USERS_MONITORING' ) ) {
        wp_schedule_event( strtotime('07:00:00'), 'daily', 'USERS_MONITORING' );
    }
}
add_action( 'USERS_MONITORING', 'run_my_script' );

Note that you need to include the related path. If you want to access the PHP file by its URL, you need to use cURL instead.

Also, as @rarst mentioned in one of his posts:

Note : WP Cron isn't guaranteed to run at precise time since it is trigerred by visits to the site. I am not confident if recurrent runs will "stick" at midnight or will slowly slip from there, you might need to readjust periodically.

本文标签: wp cronRun a php file daily at specific time