I have created a WP cron job, my code for the cron job is shown below:

    public function run_import(){
      if ( isset($_POST["run_import"])) {
        add_action( 'import_execution_event_test', array($this, 'run_execution_script' ));

                    wp_schedule_event( time(), 'every_two_minutes', 'import_execution_event_test');
     include ( plugin_dir_path( __FILE__ ) . 'views/view-import.php' );

Bear in mind here, I also have a custom schedule time here of every two minutes.

This is the function that should be executed every two minutes:

public function run_execution_script() {
        $curl = curl_init();
        curl_setopt_array($curl, array(
        CURLOPT_URL => 'http://dev2.mydevs.co.uk/wp-cron.php?import_key=_GNIHMERsu&import_id=8&action=processing',  
        CURLOPT_USERAGENT => 'Test Curl Request',
        $resp = curl_exec($curl);

All the the method does is make simple curl request, this curl request does work if I call the method manually.

So to summarize, the cron even does appear in the wp cron schedule, it appears to be being triggered every two minutes as expected, but my curl request isn't functioning from the cron.

Does anyone have any ideas why this might be?

  • Could you show a bit more context around your add_action as well as run_execution_script? Also, not a big deal but you should be using wp_remote_get() instead of cURL directly. – kovshenin Apr 4 '16 at 9:51
  • Did you register every_two_minutes ? – Sumit Apr 4 '16 at 9:59
  • @Sumit I did yeh, it now appears in the schedules array with the correct interval of 120 seconds – Liam Apr 4 '16 at 10:01
  • @kovshenin, thanks I've added some more context, I'll look in to wp_remote_get(); I didn't realize it existed. – Liam Apr 4 '16 at 10:08
  • You know that WP Cron is triggered by a website visit, so if you don't get any traffic within 2 minutes, it won't run? – TomC Apr 4 '16 at 10:36

In your code you have:

if ( isset( $_POST["run_import"] ) ) {
    add_action( 'import_execution_event_test', ...

But when wp-cron.php is spawned, there's probably no POST variable called run_import, so your action is never added, and thus not triggered.

  • Ah OK, I think I have misunderstood how this works then. My understanding was the add action was only called once initially, I didn't realize it needed to be accessible each time the cron runs. I'll give this a switch around and retry. Thanks – Liam Apr 4 '16 at 10:55
  • Yeah, what happens during a cron run is pretty much do_action( 'your_action' ); so if you have not added any callbacks to your action, then nothing's going to run. – kovshenin Apr 4 '16 at 11:11

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.