Thanks for reading my question, here is what I'm trying to achieve:
I have a PHP we开发者_高级运维b page that people visit.
I want to trigger a job that does something approximately every 100 visits(on average) to my PHP page. The frequency does not have to be extremely accurate, but in the long run, the stats should approach 100 or so.
I can not write to disk, and can not use database(due to load/performance concern). So I think this has to be done in the PHP code and some how link it to something like time. (something like generate a random number, then match it to the time, if match do the triggered job, if not match, continue).
I'm open to any ideas or suggestions. Please provide me with the sample code if possible. Thanks!
Just do something like:
<?php
$random = mt_rand(1,100);
if ($random == 100) {
trigger_your_job_here;
}
?>
Edit: I had originally used rand()
, but Alix Axel edited my response to use mt_rand()
instead. This is, of course, the right thing to do, as mt_rand()
is not only faster than rand()
(by a factor of four according to PHP's documentation), it also fixes some deficiencies of rand()
on various sytems (like on Windows, where you can only get random numbers up to 32767).
Of course, both are pseudo-random number generators and don't give proper random numbers, but for your purposes that's sufficient. You're not picking lottery numbers, for example.
You could write to a RAM disk, or memcached, if your hosting configuration supports it. That said, have you tried writing to (normal) disk to see if it really causes performance problems? The best approach here is to try it and get some metrics.
精彩评论