2

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.com/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.

  • 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 Aug 9 '17 at 9:21
  • A php file on my server ( question updated ). The native cron of my server does'nt work. – octavelhiver Aug 9 '17 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 Aug 9 '17 at 9:56
  • Ok noted. Any suggestions to do the job ? – octavelhiver Aug 9 '17 at 9:58
0

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.

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.