2013-07-11 108 views
0

我發現了一個檢查url狀態的腳本。現在我正在嘗試將其與wordpress整合。這是代碼:每天用wordpress執行php腳本

<?php 
/* 
Plugin Name: checkOnline Status 
Version: 0.1 
*/ 

add_action('cO_cron_hook', 'CheckRemoteService'); 

if(!wp_next_scheduled('cO_cron_hook')) { 
wp_schedule_event(time(), 'daily', 'cO_cron_hook'); 
} 

register_deactivation_hook(__FILE__, 'bl_deactivate'); 

function bl_deactivate() { 
$timestamp = wp_next_scheduled('cO_cron_hook'); 
wp_unschedule_event($timestamp, 'cO_cron_hook'); 
} 

function CheckRemoteService($atts) { 
extract(shortcode_atts(array(
    'url' => 'http://', 
    'cache' => '600', // 60*10 (10 minutes) 
    'online' => 'Online', // Custom online msg 
    'offline' => 'Offline' // Custom online msg 
), $atts)); 

$CachedStatus = 'cstatus_' . $url; 
$cachedposts = get_transient($CachedStatus); 
if ($cachedposts !== false) { 
return $cachedposts; 
} else { 

// Sometimes its best to change to a custom agent message 
// so you know where requests are coming from. 

$agent = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Win64; x64; Trident/5.0)"; 
$ch = curl_init(); 
curl_setopt ($ch, CURLOPT_URL,$url); 
curl_setopt($ch, CURLOPT_USERAGENT, $agent); 
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1); 
curl_setopt ($ch,CURLOPT_VERBOSE,false); 
curl_setopt($ch, CURLOPT_TIMEOUT, 5); 
curl_setopt($ch, CURLOPT_NOBODY, 1); 
curl_setopt($ch,CURLOPT_SSL_VERIFYPEER, FALSE); 
curl_setopt($ch,CURLOPT_SSLVERSION,3); 
curl_setopt($ch,CURLOPT_SSL_VERIFYHOST, FALSE); 
curl_exec($ch); 
    $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE); 
    curl_close($ch); 
    if($httpcode >= 200 && $httpcode < 400) { 
    return $online; 
    } else { 
    return $offline; 
    } 

set_transient($CachedStatus, $return, $cache); 
return $return; 
} 
} 
add_shortcode('checkmyurl','CheckRemoteService'); 

?> 

我想是每天只運行一次該代碼。如何在刷新或訪問使用簡碼的頁面時使其無法運行?我需要大約50個站點的顯示狀態,並且頁面需要超過10秒才能加載。 對不起,這個簡單的問題(我是一個noob這個),但我找不到解決方案。 謝謝。

編輯。使用http://wordpress.org/plugins/crony/

+0

名稱['cO _ ** cron ** _ hook'](https://en.wikipedia.org/wiki/Cron)是一個提示。 – PeeHaa

+0

WordPress的cron似乎有用,功能是預定的。我的問題是避免它在進入網站和刷新頁面時加載。謝謝。 –

回答

1

解決您可以使用wp_schedule_event()安排重複執行的任務。

wp_schedule_event()documentation):

時刻表將由WordPress的動作芯上的特定間隔執行的鉤,通過指定。如果預定的時間已過,某人訪問您的WordPress網站時會觸發此操作。查看插件API獲取鉤子列表。

每天安排一個事件,你會做這樣的事情:

function someFunc() { 
    wp_schedule_event(time(), 'daily', 'mydailyEventHook'); 
} 

希望這有助於!

+0

如果我刷新頁面,此塊的腳本執行?謝謝。 –

+0

當我刷新頁面時,我使用50個簡碼獲取50個站點的狀態,腳本始終運行(超過10秒)。所以我需要在訪問該頁面或刷新頁面時阻止此腳本執行的操作。用戶訪問頁面和腳本運行(超過10秒),用戶刷新頁面和腳本再次運行。用戶只能看到來自cron的腳本結果。謝謝。 –

+0

我解決了這個問題:http://wordpress.org/plugins/crony/ –