3

I have the following code that creates a CSV and then sends an email:

function generate_and_send_csv()
  {

    // Removed CSV code for ease of reading
    wp_mail('email@address.com', 'New Data Files', 'You have received new data files.', $headers, $filepath);

  }
//Create the cron event
if (!wp_next_scheduled('generate_send_csv')) {
    wp_schedule_event('1488934800', 'daily', 'generate_send_csv');
}
// Run it
add_action('generate_send_csv', 'generate_and_send_csv');

I then have the following cron set up in cPanel:

php /home/user/public_html/wp-cron.php

After installing the Cronjob Scheduler by chrispage1 plugin, I can see the plugin is correctly scheduling the cron job for 1AM every day. This runs fine, but for some reason I get the email twice.

I know it can't be anything in my code because when I click the "run" option in the Cron Scheduler plugin, I get the email once. Are there any known issues with WordPress running duplicate cron jobs?

0

I tried WP Crontrol instead and it turned out that two cron jobs were being created for generate_send_csv. To fix this, I created the crons within activation hooks and deactivation hooks as follows:

register_activation_hook( __FILE__, 'my_activation' );
add_action( 'generate_send_csv', 'generate_and_send_csv' );

function my_activation() {
    wp_schedule_event('1488979800', 'daily', 'generate_send_csv');
}

register_deactivation_hook( __FILE__, 'my_deactivation' );

function my_deactivation() {
    wp_clear_scheduled_hook( 'generate_send_csv' );
}
2
  • Hi, I'm having the same problem, but I can't rely on activation hooks because I schedule events dynamically, I can't go by deactivating activating the plugin every time an user creates a new scheduled processing event. This seems to be a fairly common problem with WP but there seems be no proper way to solve this problem. Do you have any other ideias? – Guilherme Vaz Nov 26 '20 at 16:54
  • I ended up using the Transients API, as suggest in 106028 – Guilherme Vaz Nov 26 '20 at 19: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.