简体   繁体   中英

comparing timestamps

HI, My php is very rusty and I can't quite remember how to do this.

I have a script that i only want to call every 15 minutes. I've created a table called last_updated. What I want to do is have some code at the top of my script that queries this last_updated table and if now() minus the last updated is greater than 15 minutes then run the script and also update last_updated to now...if it isn't don't run the script. Does this make sense?

Now I know when I'm updating last_updated I need to use now() To put a new timestamp in but I;m not sure how to do the comparing of now with the db value to see if it's greater then 15 mins.

Any ideas

<?php
$pdo = new PDO('mysql:host=your_host;dbname=your_database', $user, $password, array(PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION));

// query the database. change 
$stmt = $pdo->query('SELECT UNIX_TIMESTAMP(last_updated_date) FROM last_updated ORDER BY last_updated_date DESC LIMIT 1');

$lastUpdatedTimestamp = $stmt->fetch(PDO::FETCH_COLUMN);

if ((time() - $lastUpdatedTimestamp) > (60 * 15)) {
    touch($file);
    // do stuff
}

time() gives you the current time in seconds. You should probably unroll 60 * 15 to 900, I just provided it with both numbers to illustrate what was going on.

Also, a file might be better for this than a database table. Have a look at the touch() function. It changes the modification time of a file, or creates an empty file with the current time as the mod time if it doesn't exist. You can check the file mod time with filemtime()

<?php
$lastUpdated = null;
$file = '/path/to/writable/file/with/nothing/in/it';

if (file_exists($file)) {
    $lastUpdated = filemtime($lastUpdated);
}

if (!$lastUpdated || (time() - $lastUpdated) > 900) {
    touch($file);
    // do stuff
}

You seem to use MySQL as the DBMS. In that case and if you want you can let MySQL do most of the work:

SELECT
  pit < Now()-Interval 15 Minute as mustUpdate
FROM
  last_updated
WHERE
  siteId=?

pit is your DateTime field and siteId is some condition you may have if you store more than one record in the table (which sounds like a good idea to me).
The result (if there is such a record with siteId=? ) contains a field mustUpdate which either contains 0 or 1 , 1 indicating that the value of pit is more than 15 minutes in the past.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM