开发者

Need code critique for time interval test script PHP

开发者 https://www.devze.com 2023-01-12 03:01 出处:网络
Hey again!I\'m trying to write a set of scripts 开发者_如何学Pythonthat will run on a page only if it has been more than 15 minutes since they last ran.Basically, an automated script updates a databas

Hey again! I'm trying to write a set of scripts 开发者_如何学Pythonthat will run on a page only if it has been more than 15 minutes since they last ran. Basically, an automated script updates a database of mine every half hour--and a page which displays that information and updates session variables must obviously query the database whenever it is opened.

So in order to minimize queries but also stay on the safe side, I figured that the session variables would only be updated from the database if it had been more than fifteen minutes since that page was last viewed. I wrote up some code, and I was hoping you guys could take a look at it before I try implementing it?

if(!isset($_SESSION['time_next'])){

    $_SESSION['time_next'] = time() + (15 * 60);
                                     //15 minutes   
}
else if(time() >= $_SESSION['time_next']){

    //update all the session variables, etc...

    $_SESSION['time_next'] = time() + (15 * 60);    
}

What do you think? Will this work?


It will work, but you can write it shorter and cleaner*. Do note that the session is visitor-bound, so when 10 people request the page, you will get 10 instances running your update.

do_update_if_needed(15);

function do_update_if_needed($minutes)
{
    if ( isset($_SESSION['time_next']) && time() < $_SESSION['time_next'] ) return;

    // either time_next was not set, or it's time to update, so set next time:

    $_SESSION['time_next'] = time() + $minutes*60;

    // do your thing!
}

You could also write a simple file containing the last time (or using its last-modified time). In general I think it is better to record the last time than the next time, since the last time actually tells something that has happened, not just "a plan" (which leads to questions, like who's plan was it? why? etc.)

*cleaner refers to: 1) put it in a function, and 2) do the calculation in one place, not in two branches of if


You probably want to create DAEMONS for this sort of thing.

You definitely should not go the way you're headed as others have better explained.

You also should not use cron because if the process takes more that the time you think it should take it will overun the other process. That could make a mess of you app and it's really not an elegant solution.

A deamon will run in the background in a silent fashion. Will deal with all the work-load you need, wont overwrite itself and can also run in a pre-set amount of time.

Take a look at this excellent tutorial by Kevin van Zonneveld.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号