How to periodically update server-side value on we

2019-08-21 14:09发布

问题:

I have a timestamp stored in a MySQL database, and I want to periodically (say every second), update the difference between the current time and the timestamp value stored on the database (of course without reloading the page) to show something like a 5 minute count-down timer. Right now. I'm thinking use setTimeout to periodically fire an AJAX request that gets this value. Is this the best approach? Instead, should I just run a client-side timer, and then sync it with the server-side timestamp every minute or so?

Note: This timer is responsible for an important function on my website, so it should be reasonably accurate.

Edit: I don't need a cron job, I just need a countdown timer that updates on a webpage like from 5:00 to 4:59 to 4:58... etc, automatically. If you're familiar with the one Megaupload had before it was shutdown, I need something similar.

回答1:

Because of the nature of the way Javascript works, exact timers are next to impossible to achieve (see this for more details).

However, you can do something very close to it, and I'd suggest that what you want to do is do it all client-side (which is user-tamperable but minimal resource consumption) and more importantly use server side validation to prevent the user being able to tamper with it. So you set a value in the database at the beginning that says "don't accept the submit before x time" and then the client can handle the timer.

Here is a very small example of how it can be done



回答2:

It depends on what do you want to accomplish.

If you need to process something that is related to the website in general each 5 minutes for example then use a cron job.

If you want to improve user experiance by updating the comments list per example then use ajax.



回答3:

So you want a server with all this stress.

One can assume that the clock on both server and client has a second that lasts as long on both and may take a week (if very bad) diverge.

But the client may think it is 1st Jan 1972 at midnight but your server thinks it is 14:25 on Fri 10th Aug 2012.

So just pass that date from the server to the client. Work out the diff. On the page you can put the servers date/time on the page just using Javascript.

As to the web site (server bit) just rely on the servers time. That you can control.

The countdown timer is just a pleasantry. But the server stuff is your asset and where you make your business. If you rely on the client some nasty person can just reset the time.



回答4:

You can make a script that does that, and you can run it every second or so, depending on what OS your server runs on, with:

if linux { chronjob } http://www.thegeekstuff.com/2011/07/php-cron-job/

else if windows { windows scheduler } How do I run a PHP script using windows schedule task?

That's the safest and most efficient way to run client-side scripts.