WP Cron作业在每次加载页面时运行 [英] WP Cron Job Runs On Every Page Load

查看:88
本文介绍了WP Cron作业在每次加载页面时运行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在努力处理wp cron工作,并且一直在使用以下代码片段,该代码片段应该每小时发送一次电子邮件到指定的电子邮件地址,当然前提是访问者已经访问过网站并触发了工作(我已经了解到,wp cron工作显然不是真正的计时工作).

现在,该工作的工作方式是将电子邮件发送到该电子邮件地址,但是存在两个问题:

  1. 每个同步作业多次发送电子邮件
  2. Cron作业似乎在每次页面加载时都会触发,即使它每小时不应运行超过一次

这是代码(摘自 wp_schedule_event不触发):

  if(!wp_next_scheduled('prefix_hourly_event')){wp_schedule_event(time(),'hourly','prefixhourlyevent');}add_action('prefixhourlyevent','prefix_do_this_hourly');函数prefix_do_this_hourly(){wp_mail('myemail@gmail.com','Cron正在工作','Cron正在工作:','','');} 

任何人都可以给我一个想法,为什么每小时不只发送一封电子邮件吗?//Mega WP Noob

解决方案

您正在检查事件是否已安排,何时未找到该事件,则使用另一个名称进行注册.不匹配是导致它在每次页面加载时运行的原因.

更改此:

  if(!wp_next_scheduled('prefix_hourly_event')){ 

对此:

  if(!wp_next_scheduled('prefixhourlyevent')){ 

我还将查看您是否可以检查一次计划,而不是每次加载页面一次.例如,如果您正在编写插件,则可以在插件激活挂钩上触发它.

进一步阅读: https://codex.wordpress.org/Function_Reference/wp_schedule_event

I am trying to wrap my head around wp cron jobs and have been playing around with the following snippet of code, which is supposed to send an email to the specified email address once an hour, provided of course that a visitor has visited the site and triggered the job (wp cron jobs aren't apparently real chron jobs, I've come to understand).

Now, the job works in that an email gets sent to the email address, but there are two problems:

  1. The email gets sent multiple times per chron job
  2. Cron jobs seem to be triggered on every page load even though it's not supposed to run more than once an hour

Here's the code (retrived from wp_schedule_event not firing):

if ( ! wp_next_scheduled( 'prefix_hourly_event' ) ) {
    wp_schedule_event( time(), 'hourly', 'prefixhourlyevent');       
}

add_action( 'prefixhourlyevent', 'prefix_do_this_hourly' );

function prefix_do_this_hourly() {       
   wp_mail('myemail@gmail.com','Cron is working', 'Cron is working: ','','');
}

Would anybody be able to give me an idea of why not just one email gets sent every hour? //Mega WP Noob

解决方案

You're checking if an event is scheduled and when it's not found you're registering it under a different name. The mismatch is what's causing it to run on every page load.

Change this:

if ( ! wp_next_scheduled( 'prefix_hourly_event' ) ) {

To this:

if ( ! wp_next_scheduled( 'prefixhourlyevent' ) ) {

I'd also look at whether you can check the schedule once rather than on each page load. If you were writing a plugin for example you could fire it on the plugin activation hook.

Further reading: https://codex.wordpress.org/Function_Reference/wp_schedule_event

这篇关于WP Cron作业在每次加载页面时运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆