我知道wp_schedule函數會在打開瀏覽器選項卡並且不關閉它時在後臺運行一個類似於ajax的cron。那麼,爲什麼我的功能無法實現?爲什麼wordpress中的wp_schedule函數不起作用?
我改變了我的coumputer時間=我的wordpress設置時間=在php.ini中的GMT時間。但它仍然不起作用,下面是我的代碼。我把它放在一個wordpress插件裏面。所以我必須做什麼?
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();
那麼,我的代碼有什麼問題? –
我已經擴展了答案。 –
嘿,你,我成功了。但我的代碼只是如果我刪除:如果(!wp_next_scheduled('wpwhosonline_update')){。但是,如果我不刪除它,它會運行重複多次。 –