2017-06-03 100 views
0

我知道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(); 

回答

0

WordPress檢查它是否只有當有人訪問網站時纔有cron任務。如果您在2分鐘內爲您設置了下一個活動,並且下次訪問您的網站將在10小時內完成,那麼您的活動將在10小時內(即時訪問)觸發,但不會在2分鐘內觸發。

它不像ajax,也不需要打開瀏覽器。 WP_Cron在後臺運行。

如果您的網站經常訪問,您可以放心,計劃的活動將在選定的時間運行。

UPDATE

什麼是你的代碼錯誤。

wp_schedule_event被錯誤地調用。

第一個參數是定義第一個事件執行的時間。從UNIX紀元開始(1970年1月1日)開始,以毫秒爲單位。你在做什麼,你告訴從現在開始你的活動的第一輪運行10毫秒。順便問一下,WordPress會盡快做到,但time()+ 10完全沒有意義。只需將time()作爲第一個參數。

第二個參數不能爲空。它必須指定事件的重現。 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; 
} 

此示例設置間隔ten_seconds可以在wp_schedule_event使用。最後,你的電話應該是這樣的:

wp_schedule_event( time(), 'ten_seconds', 'ga_order_syn'); 
+0

那麼,我的代碼有什麼問題? –

+0

我已經擴展了答案。 –

+0

嘿,你,我成功了。但我的代碼只是如果我刪除:如果(!wp_next_scheduled('wpwhosonline_update')){。但是,如果我不刪除它,它會運行重複多次。 –

相關問題