Skip to content

Commit

Permalink
✨ Update cache prices with cron job
Browse files Browse the repository at this point in the history
  • Loading branch information
cristianlivella committed Nov 21, 2021
1 parent d4890af commit 0368c27
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 3 deletions.
4 changes: 2 additions & 2 deletions src/app/Utils/CryptoInfoUtils.php
Original file line number Diff line number Diff line change
Expand Up @@ -246,7 +246,7 @@ private static function fetchCryptoDataFromDb($ticker, $date) {
return;
}

$currentTime = time();
$currentTime = defined('FAKE_CACHE_EXPIRATION') ? (time() + (60 * 60)) : time();
$stmt = DbUtils::getConnection()->prepare('SELECT date, quote, ticker, name, found FROM cache WHERE ticker = ? AND date >= ? AND date <= ? AND (expiration = 0 OR expiration > ?)');
$stmt->bind_param('sssi', $ticker, $firstDate, $lastDate, $currentTime);
$stmt->execute();
Expand Down Expand Up @@ -315,7 +315,7 @@ private static function fetchCryptoDataFromApi($ticker, $date) {
foreach ($values AS $value) {
$price = floatVal($value['price_eur']);
$found = $value['found'] ? 1 : 0;
$expiration = time() + $value['cache_max_age'];
$expiration = time() + ($value['found'] ? $value['cache_max_age'] : min($value['cache_max_age'], 60 * 60 * 24 * 30));
$stmt = DbUtils::getConnection()->prepare('INSERT INTO cache (ticker, name, date, quote, expiration, found) VALUES (?, ?, ?, ?, ?, ?) ON DUPLICATE KEY UPDATE quote = ?, expiration = ?, found = ?');
$stmt->bind_param('sssdiidii', $value['ticker'], $value['name'], $value['date'], $price, $expiration, $found, $price, $expiration, $found);
$stmt->execute();
Expand Down
21 changes: 20 additions & 1 deletion src/cron.php
Original file line number Diff line number Diff line change
@@ -1,11 +1,16 @@
<?php
use CrypTax\Utils\DbUtils;
use CrypTax\Utils\CryptoInfoUtils;

// delete old report files

require_once __DIR__ . '/config.php';
require_once __DIR__ . '/vendor/autoload.php';

if (PHP_SAPI !== 'cli' || isset($_SERVER['HTTP_USER_AGENT'])) {
die();
}

// delete old report files
foreach (new DirectoryIterator(dirname(__FILE__) . '/tmp') AS $fileInfo) {
if ($fileInfo->isDot()) {
continue;
Expand All @@ -15,3 +20,17 @@
unlink($fileInfo->getRealPath());
}
}

// update cached prices that expire in the next 60 minutes
define('FAKE_CACHE_EXPIRATION', true);

$expirationTime = time() + (60 * 60);
$stmt = DbUtils::getConnection()->prepare('SELECT date, ticker FROM cache WHERE expiration < ?');
$stmt->bind_param('i', $expirationTime);
$stmt->execute();
$result = $stmt->get_result();
$stmt->close();

while ($resultArray = $result->fetch_assoc()) {
CryptoInfoUtils::getCryptoPrice($resultArray['ticker'], $resultArray['date']);
}

0 comments on commit 0368c27

Please sign in to comment.