I'm building a webapp. HTML+AJAX <--> PHP <--> MySQL; very traditional. What I need to do is have some state that all sessions can read from, and something that drives state changes even when there are no users looking at the site.
A simple example would be a counter. We start the counter running from zero, and then whenever any user connects to the website, they see the current value of the counter. Even if nobody is looking at the website, the counter still increases. Everyone looking at the website sees the same value at the same time.
What's the best way to implement this? It seems like I should be able to do this without resorting to storing values in the database and having everyone query the database for state. But I don't know how to have PHP running when nobody is connected. Do I need a fourth component? I don't have my own webserver, this stuff is all hosted at some off the shelf place that setup the environment for me, but they seem to have most up-to-date and reasonable stuff one would expect in this sort of stack.
Clearly this isn't my area of expertise, so a开发者_StackOverflowny nudges in the right direction are appreciated.
You could set a global PHP variable and if your web host allows it in your control panel set up a cron job to run a php script in your app that increments the variable every certain amount of minutes.
http://en.wikipedia.org/wiki/Cron
Usually web hosts will have a cron scheduler app in their control panel that lets you pick what script to run and at what time intervals.
Could you explain what exactly you want to do in the background though? Whatever the case, it sounds like you're going to want to look into setting up a cron task to execute a console based php script to perform this additional functionality. You can schedule cron tasks to execute however frequently you wish. Setting up cron tasks can be done from any control panel worth its salt (cPanel, Plesk, Exim, whatever).
As far as actually keeping this information available to all sessions in your main front-facing PHP code, you could store the information in a Cache (using Memcache)
What makes the counter increase?
You could use a cron job.
To have the state persist over all connections, it will either need to be stored in a database or as a file (which a database really is anyway).
精彩评论