使用外部Cron服务每天仅运行一次Cron作业

时间:2016-11-02 作者:Kev

我有一个特定的任务,需要每天运行一次(而且只运行一次)。由于wp cron每天运行的不确定性,我使用setcronjob。com来激活脚本。

URL setcronjob。com调用是:

http://mydomain.co.uk/wp-cron.php?doing_wp_cron

以及setcronjob中的每日执行。com设置设置为1。

在wp配置中。php我添加了一行:

define(\'DISABLE_WP_CRON\', true);
脚本本身是一个插件,代码(减去插件内容)如下:

<?php
add_action(\'init\',\'kl_create_single_schedule\');
add_action(\'kl_single_cron_job\',\'kl_single_cron_function\');

function kl_single_cron_function(){
  $todayis = date("Y-m-d");
  $thenwas =  date(\'Y-m-d H:i:s\',  strtotime($todayis . \'-360 day\'));
  global $wpdb;         
  $renewals = $wpdb->get_results("SELECT * FROM {$wpdb->users} WHERE date({$wpdb->users}.user_registered) = \'" . $thenwas ."\'");                
  foreach ( $renewals as $renewal ) {
    $thename = $renewal->display_name;
    $theemail = $renewal->user_email;
    $to      = $theemail;
    $subject = \'Important information about your Subscription\';
    $message = \'Hi \' . $thename . ",\\n\\r\\n\\rIn five days your subscription will renew and another year\'s subscription (£45) will be taken from your PayPal account.\\r\\n\\r\\nIf you want to stay with us you don\'t need to do anything, it will happen automatically. If you want to cancel your subscription you can do this via your PayPal account, or if you prefer simply reply to this email or send a new email to us at [email protected] requesting for your subscription to be cancelled.  \\r\\n\\r\\nRegards,\\r\\n\\r\\Kev from Domain Name.";
    $headers = \'From: [email protected]\' . "\\r\\n" . \'Reply-To: [email protected]\' . "\\r\\n" . \'X-Mailer: PHP/\' . phpversion();
    mail($to, $subject, $message, $headers);
  } 
}

function kl_create_single_schedule(){
  //check if event scheduled before
  if(!wp_next_scheduled(\'kl_single_cron_job\'))
  //schedule event to run after 1 day
  wp_schedule_single_event (time()+0001, \'kl_single_cron_job\');
}
?>
然而,插件每天运行多次。

我是否正确地认为:

wp_schedule_single_event (time()+0001, \'kl_single_cron_job\');
实际上应该是:

wp_schedule_single_event (strtotime(\'+1 day\'), \'kl_single_cron_job\');

1 个回复
最合适的回答,由SO网友:jgraup 整理而成

wp_schedule_single_event\'s$timestamp 是您希望事件发生的时间。这必须是UNIX时间戳格式。WP cron使用UTC/GMT时间,而不是本地时间。使用time(), 在WordPress中总是GMT。

time() 自Unix纪元以来的秒数

如果要添加一天,则需要添加秒数:

time() + (24 * 60 * 60)
因此,您需要使用:

if ( ! wp_next_scheduled( \'kl_single_cron_job\' ) ) {

    wp_schedule_single_event( time() + 86400, \'kl_single_cron_job\' );

}
\'daily\' 具有wp_schedule_event:

if ( ! wp_next_scheduled( \'kl_single_cron_job\' ) ) {

    wp_schedule_event( time(), \'daily\', \'kl_single_cron_job\' );

}