Timer based status changes that are saved to database
I have a PHP website using a MySQL database.
We have items that users create, that are on a timer, and once this timer has counted down, without user intera开发者_开发知识库ction (basically next time someone sees it) the status needs to have changed.
I'm not sure how to implement this in a way to be accurate to the minute.
So we have an object X, that expires at 10:15pm tommorrow, and the next person to see object X after that time has to see it as expired.
Is the correct way to do this to be the next time object X is loaded we check if it's expired, and if so, update the database?
What happens if 10 people load object X at the same time after it's expired, what's to prevent some sort of race condition from all 10 requests attempting to update the database?
Is there a cron job that runs every minute that I can some how make use of, or any type of timer in MySQL to kick off every minute checking for these and running a script?
I have several ideas on how it -could- be done, like those listed above, but I'm not sure what the most practical is, or what the standard way to do it is as I'm positive someone has solved this problem before.
Is the correct way to do this to be the next time object X is loaded we check if it's expired, and if so, update the database?
Why do you need to update the database? It seems like you might have some redundancy in your DB table - from what you've said, it sounds like you have (for instance) an is_expired
column and then an expires_at
column.
Why not just get rid of the is_expired
column? It's cheap to compare 2 integers, so when you want to determine if something is expired, just fetch the expires_at
column and compare with the current time. This avoids any race conditions with expiry, since nothing in the DB changes.
You can do it with cron
of course. Or with javascript native function setInterval( "checkFunction()", 10000 );
to alter the db. Or you could use a date field in DB and check for expiration
Make a field date_to_expire as DATE , enter the expiration date and everytime you query for it check to see if the item is expired (this can go up to seconds)
精彩评论