我正在开发WordPress插件,并在那里添加了对wp cron的支持。请参见以下代码:
function __construct(){
//Cron Job
add_action(\'init\', array($this,\'g_order_sync\'));
add_action(\'ga_order_syn\', array($this,\'sync_order\'));
add_filter(\'cron_schedules\',array($this,\'my_cron_schedules\'));
}
function my_cron_schedules($schedules){
if(!isset($schedules["10sec"])){
$schedules["10sec"] = array(
\'interval\' => 10,
\'display\' => __(\'Once every 5 minutes\'));
}
return $schedules;
}
public function g_order_sync(){
if( !wp_next_scheduled(\'ga_order_syn\') ) {
wp_schedule_event( time(), \'10sec\', \'ga_order_syn\' );
}
}
public function sync_order(){
$content = "some text here";
$fp = fopen($_SERVER[\'DOCUMENT_ROOT\']. "/myText.txt","wb");
fwrite($fp,$content);
fclose($fp);
}
当我使用打印cron时
print_r( _get_cron_array() );
, 它告诉我我的克朗(
ga_order_syn
) 每10秒计划一次,但
sync_order()
函数不在创建文件
DOCUMENT_ROOT
. 如果我向
wp_mail()
功能,它不会向我发送邮件。
我的代码有什么问题?为什么不起作用?
最合适的回答,由SO网友:jgraup 整理而成
你是否正确地构建了这个类?文件可写吗?是否需要时间间隔,或者如果不存在计划项目,是否可以添加计划项目。
此示例正在运行,并设置了一个事件10
几秒钟后。
<小时>
wp_schedule_event( time() + 10, null, \'ga_order_syn\' );
<人力资源>
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() {
if ( ! wp_next_scheduled( \'ga_order_syn\' ) ) {
wp_schedule_event( time() + 10, null, \'ga_order_syn\' );
}
}
// 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();