Php 为什么wordpress中的wp_调度功能不起作用?
我知道当您打开浏览器选项卡而不是关闭它时,wp_schedule函数将使类似cron的ajax在后台运行。那么,为什么我的函数不能让它工作呢 我更改了我的计算机时间=我的wordpress设置时间=php.ini中的GMT时间。但它仍然不起作用,下面是我的代码。我把它放进了wordpress插件中。那我该怎么办Php 为什么wordpress中的wp_调度功能不起作用?,php,wordpress,schedule,Php,Wordpress,Schedule,我知道当您打开浏览器选项卡而不是关闭它时,wp_schedule函数将使类似cron的ajax在后台运行。那么,为什么我的函数不能让它工作呢 我更改了我的计算机时间=我的wordpress设置时间=php.ini中的GMT时间。但它仍然不起作用,下面是我的代码。我把它放进了wordpress插件中。那我该怎么办 class CronTest { function __construct() { add_action( 'init', array ( $this, 'g_order_sy
class CronTest {
function __construct() {
add_action( 'init', array ( $this, 'g_order_sync' ) );
add_action( 'ga_order_syn', array ( $this, 'sync_order' ) );
}
// init
public function g_order_sync() {
try{
if ( ! wp_next_scheduled( 'ga_order_syn' ) ) {
wp_schedule_event( time() + 10, null, 'ga_order_syn' );
}
}
catch(Exception $ex)
{
echo "<p>The error: " . $e->getMessage() . "</p>"; //display error
}
}
// cron job
public function sync_order() {
$content = time() . ": some text here";
$this->_write_content ($content);
}
// write content
private function _write_content( $content = '') {
$path = $_SERVER[ 'DOCUMENT_ROOT' ] . "/myText.txt";
if( is_writable($path)) {
$original = file_get_contents($path);
$original .= PHP_EOL . $content;
$fp = fopen( $path, "wb" );
fwrite( $fp, $original );
fclose( $fp );
} else {
// log error here
}
}
}
// must initialize the cron class
$cron_test = new CronTest();
类测试{
函数_u构造(){
添加动作('init',数组($this,'g_order_sync');
添加动作('ga_order_syn',数组($this,'sync_order'));
}
//初始化
公共函数g_order_sync(){
试一试{
如果(!wp_next_scheduled('ga_order_syn')){
wp_计划_事件(time()+10,null,'ga_order_syn');
}
}
捕获(例外$ex)
{
echo“错误:“.$e->getMessage()”“;//显示错误
}
}
//cron作业
公共函数同步顺序(){
$content=time();
$this->\u write\u content($content);
}
//写内容
私有函数_write_content($content=''){
$path=$\u服务器['DOCUMENT\u ROOT']。“/myText.txt”;
if(可写($path)){
$original=文件内容($path);
$original.=PHP_EOL.$content;
$fp=fopen($path,“wb”);
fwrite($fp,$original);
fclose($fp);
}否则{
//此处记录错误
}
}
}
//必须初始化cron类
$cron_test=新的CronTest();
WordPress只在有人访问站点时检查是否有cron任务。如果您将下一个事件设置为2分钟后运行,并且下一次访问您的站点将在10小时后启动,则您的事件将在10小时后(立即启动访问),但不会在2分钟内启动
它不像ajax,不需要打开浏览器。WP_Cron在后台运行
如果您的站点经常被访问,您可以确信计划的事件将在选定的时间运行
更新
你的代码有什么问题
wp\u schedule\u事件
调用不正确
第一个参数是定义第一个事件执行的时间。从UNIX纪元(1970年1月1日)开始,以毫秒为单位。你在做什么,你告诉自己从现在开始,在10毫秒内第一次跑完你的比赛。顺便说一下,没问题,WordPress会尽快完成,但time()+10毫无意义。只需将time()保留为第一个参数
第二个参数不能为null。它必须指定事件的重复发生。WordPress有3个预定义的时间间隔:每小时、两天和每天。如果它们都不合适,则必须在特殊挂钩中设置:
add_filter( 'cron_schedules', 'example_add_cron_interval' );
function example_add_cron_interval( $schedules ) {
$schedules['ten_seconds'] = array(
'interval' => 10,
'display' => esc_html__( 'Every Ten Seconds' ),
);
return $schedules;
}
此示例设置间隔10秒
,可在wp\u计划\u事件
中使用。最后,您的呼叫应如下所示:
wp_schedule_event( time(), 'ten_seconds', 'ga_order_syn' );
我已经扩展了答案。嘿,你,我成功了。但是如果我删除,我的代码就正常了:if(!wp_next_scheduled('wpwhosonline_update')){。但是如果我不删除它,它将多次重复运行。