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 interaction (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)
Related
I'd love to create great things with number based stuff.
I totally have no idea how / where should I start.
Let's say users have to register then log in to the site to use this feature (already done this).
I tried to save their registration date in timestamp and calculate their value (the one that i need to increment) from the elapsed timestamp since registration. It was working, but when I set a maximum to this value, and then raised it's maximum, it just jumped to the new maximum (since the time was still going). Btw, this thing needs to be working even if the user is completely logged out, and also not on the site. (so it's server sided)
So let's say I need to increment this value by 550 an hour, but after the first hour elapsed the incrementation grows to 650, after the second hour grows to 750 and so on... and as soon as it reached 3272 it must stay there.
It's also important to visually upgrade this value LIVE. So the user doesn't have to refresh the page every time he/she wishes to take a look at their new value. I guess the hard part is that to calculate every second's incrementation value to match the value of the hour. Okay not that hard I guess it must be like 650/60/60 = 1 second
Best Regards,
Henrik
It is not clear what you are trying to do, but you have multiple options.
You can use timestamp itself as a increment value.
Or
You can use cron-jobs. (Google if you need more information about this)
Create a cron to automatically increment your mysql value and set the interval.
Hope this helps.
so first of all i checked and researched this question in stackoverflow and google but there no similar question.
i checked Count number of consecutive visits and SQL Query: Visited the site each day for 30 consecutive days but it doesn't help.
so my question is where to implement this action of testing if a user has visited the site for a consecutive x time, in the links that i put there they check in server side, but i think it's not very optimised because each time the user visits the website a query is triggered to check if todays date is equal or higher than LastVisit date.
in my application i already do query every time the user loads a page to retrieve his information but if i add an
update userInfo
set DaysConsecutivelyVisited=DaysConsecutivelyVisited+1
when DATEDIFF(CURDATE(),LastVisit)=1
then i'll have two queries every time the user loads the page, so i tought maybe it's better if i do this in client side rather than in server side. I'll put an attribute or hidden span in the document
<body data-lastvisit="2012-03-25" >
and in the javascript i'll do the analysis and if the $("data-lastvisit") is equal to yesterday i'll send an ajax reqeuest to update the DaysConsecutivelyVisited
what do you think, is it a good idea ?
You'll need a parameter to compare to.. which is - unfortunately - always the data inside your database table. The only thing you can do is to retrieve the userinfo on pageload, which most likely includes a field last_visited. If the date is not equal to todays date, registered it.
Furthermore, I'd say create a field consecutive_visits and reset to 0 in case the date's difference is larger than a day and increment it in case there's a day or less difference. This way you'd always have the amount of consecutive visits in the userobject after fetching it on pageload.
I absolutely do not see any need for an ajax request in this case. It's just a compare of the current user data with a Date() instance or timestamp. All calculating can be done serverside and there's only need for an extra MySQL query in case the values are different.
For a two-player game, I need to send updated data to player every 30 seconds.
I have a table (ideally 4 tables) from where I need to select data and sent to user once he/she login. Since it is multi-player interaction game, data needs to be sync every 30-60 seconds.
My problem is, I've a very heavy query to run every 30-60 seconds. So ideally, I should send only updated and new rows to the player during sync (Its also a front end requirement for IPhone/Android game, app don't want whole data during every sync operation).
I went through MySQL: difference of two result sets and hope I'll get only updated/new records through SQL but problem is, how do I save result of last query.
Even if I save first result in Session (probably not recommended) that record will be useless as soon as new row inserted or updated. Updating session record again will definitely put lot of pressure on the server.
Can someone please suggest the best way to achieve this requirement; Not detailed solution, just some hint/link will be sufficient.
Basically, this isn't that hard. Let me provide you with a step plan.
Add a datetime field to each table you want to do this on
In each of your updating queries, set this field to NOW()
Make sure that the application adds the time of its last update to all its requests
Have the server add the time of the update to result it send to the app (which also sends the updated rows)
Can't you just timestamp everything?
Give every row in the tables a timestamp called something like "last_updated"
In the query, filter out all entries with a last_updated that is before the last time the query was executed (or possibly the latest last_updated that the client got the last time it called the server)
What is the best way to calculate the total time spent by a registered user on the site? ...under these conditions
1) User logs out normally.
2) User can simply close browser.
3) User can auto-login next time he comes back.
I think the best way to do this would be to find the time spent by the user on each page and keep adding them to his total time instead of checking for the whole site. But I don't know how to implement that....please help
You can't find the exact time he leaves the system, unless he logs out. Even then, he might be browsing the site while logged out.
The approximate way to do this would be to set the start time in the session and keep incrementing the time everytime he visits a page.
So the first time the user comes to your site at time T, you will
Create a session and put the start time there
Add the total time as 0
For all subsequent requests you would
Check the start time and compare that with the time now and get the difference
Add that time to the total time
This method will not give you the time the user spent on the last page. But it will give you something to work with.
You can do this with JavaScript and a separate PHP script.
The javascript code reacts to events that mean that an user is active (such as mouse/keyboard/resize events) and invokes the php script.
The php script compares the time when it last received a request to the current time and checks if the difference is over a certain threshold (i suggest something like 10-30 minutes to prevent single-click sessions from adding up) nothing happens.
If the threshold is not reached then the difference between the two timestamps is added to the total sum in the database.
Afterwards (in both cases) the last request time is set to the current time and the script ends.
If you also want to know when the user closes your website pages you can subscribe to unload events and/or implement an heartbeat script that calls a PHP script every X seconds.
you have 2 approaches, either to create a log table in your DB to track each user (by ID) logins and logouts and then calculate the time difference between the two in each record for the specific user and then sum all of that. OR you go more complex and make 4 columns in your DB->usertable (logintime 'timestamp' - logouttime 'timestamp' - lastactive 'timestamp' - onlinetime 'int') and update each column as their names say by code according to user activities. then alter the Session.php script in the System/libraries directory at line 105 exactly after if ( ! $this->sess_read()) before the system creates a new session and write a code to check if the 'logouttime' is not the same as 'lastactive' time (to avoid session timeout expiry misunderstood in the next code) if both fields not the same, update your DB to make 'logouttime' equals 'lastactive' then at line 107 exactly after: $this->sess_update(); write a code to check if the 'logouttime' equals the 'lastactive' (and you will make that happen earlier in your logout.php script) write a code to calculate the online time by the difference between the 'logintime' and the now time 'time()' and add the result to the 'onlinetime' field. but if the 'logoutime' is not the same as 'lastactive' (that meanse the user is online and making activities in your site because you are tracking him and updating the 'lastactive' field frequently) then write a code to calculate the online time by the difference between the 'lastactive' and now time 'time()' and add the result to the 'onlinetime' field. that way you have the exactly online time logged forever in the 'onlinetime' field! I hope you got me right because the examples will be a lot long of scripts (although I don't mind to share upon request). good luck.
Use the Session ID to keep track of individual sessions.
For example I made a reservation for a restaurant and it expires in 24 hours. In the reservation table of the db (MySQL), how do I automatically update the status to expired after 24 hours? What approach would you guys suggest? Thanks in advance!
Don't really know the problem you're trying to handle but I'd store the timestamp when the reservation was made and have a field which stores after what interval from the point reservation was made does it expire (24 hrs in your case) and that's it. The rest should be handled at the point where you read/display that information.
Besides if you still really want to CHANGE the value in DB go for a cron that regularly updates the DB
Running periodical tasks is usually done with cron.
Here are some instructions how to use it on drupal (which is php/mysql)
Use cron like Unreason said or MySQL events, see Create event.
using cron can be liitle difficult
just run update query by comparing timestamp value with your time limit.
it will work.
I would suggest the following two methods.
To run a cookie at the background and check it out if the time (here in this case 24hrs) ran out or not..
Store the entry in the database with DATETIME type. As we check whether the user logged in or not with session variables. In the similar way for every click in the site, call a function to check whether the time is lapsed or not.