簡體   English   中英

每天更新一次 php 腳本

[英]Updating php script one time per day

我正在制作一個 Covid-19 統計網站 - https://e-server24.eu/ 每次有人進入網站時,PHP 腳本都會從 3 個 url 解碼 JSON 並將數據存儲到一些變量中。 我想讓我的網站更加優化,所以我的問題是:是否有任何腳本可以每天更新一次變量數據,而不是每次有人訪問網站時?

謝謝,

簡單的方法創建一個腳本,它將獲取、解碼 JSON 數據並將其存儲到您的數據庫中。 然后設置一個時間間隔為 24 小時的 Cron 作業。 當用戶訪問您的站點時,從您的數據庫而不是您的 api 提供程序中獲取數據。

我建議查看 memory object 緩存。

許多高性能 PHP web 應用程序使用緩存擴展(例如MemcachedAPCuWinCache )、加速器(例如 APC、 varnish )和緩存 DB,例如 ZE111446742A1825B8ZAE462F。 設置可能有點復雜,但您可以從一個簡單的角色自己的解決方案開始( 受此啟發):

<?php
function cache_set($key, $val) {
   $val = var_export($val, true);
   // HHVM fails at __set_state, so just use object cast for now
   $val = str_replace('stdClass::__set_state', '(object)', $val);
   // Write to temp file first to ensure atomicity
   $tmp = sys_get_temp_dir()."/$key." . uniqid('', true) . '.tmp';
   file_put_contents($tmp, '<?php $val = ' . $val . ';', LOCK_EX);
   rename($tmp, sys_get_temp_dir()."/$key");
}

function cache_get($key) {
    //echo  sys_get_temp_dir()."/$key";
    @include sys_get_temp_dir()."/$key";
    return isset($val) ? $val : false;
}

$ttl_hours = 24;
$now = new DateTime();

// Get results from cache if possible. Otherwise, retrieve it.
$data = cache_get('my_key');
$last_change = cache_get('my_key_last_mod');
if ($data === false || $last_change === false || $now->diff($last_change)->h >= $ttl_hours ) { // cached? h: Number of hours.
    // expensive call to get the actual data; we simple create an object to demonstrate the concept
    $myObj = new stdClass();
    $myObj->name = "John";
    $myObj->age = 30;
    $myObj->city = "New York";    
    $data = json_encode($myObj);
    // Add to user cache 
    cache_set('my_key', $data);

    $last_change = new DateTime(); //now
    // Add timestamp to user cache
    cache_set('my_key_last_mod', $last_change);
}

echo $data;

瞧。

此外; 您可以查看客戶端緩存和許多其他內容。 但這應該給你一個想法。

PS:大多數 memory 緩存系統允許定義生存時間 (TTL),這使得這更加簡潔。 但我想讓這個例子保持無依賴。 這里省略了緩存清理。 只需刪除臨時文件。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM