I have a web application in PHP and Javascript where i want to apply a time based question generation. I have preset of code that will be executed at a specific time which will generate the question.
Now i am thinking that how can i apply this. Here are some the information regarding the web
Web is running on wamp server and there are almost 100 users used it regularly (every day). They login in the website two time between 9-11am and 2-6pm.
The question geneartion time should be at 4pm.
Now, i can make use SetTimeOut and Javascript Date object in order to acheive the desire functionality: Here
function checkVotingQuestionTime()
{
var currentTime = new Date();
if(currentTime.getHours() >= 16 && currentTime.getHours() < 23)//check the time from user OS
{
checkVoteQuestionGenerated();
}
}
function checkVoteQuestionGenerated(){
//query to php check question exists
//if no
//then generate question
}
And Register it at document ready event in main page(after login). This code will be open for all users.
$jq(document).ready(function() {
setInterval(checkVotingQuestionTime, 60000);
}
As it appear that, this is not feasible code, because
It will be run from every client (set timeout and server hit
regularly and if i also get time from server than it will more often hit on server)
A user can change the system time to run above code.
Multiple question can be generated if two clients simultaneously check that the question is not generated so generate the question.
So how can I control above limitations or is there any other proper solution available?
Having 100 clients poll the server every few minutes is not a big deal. Every time they open a page on your website that's in effect polling the server. So moving the date check to php on the server side is the best solution for what you have currently set up.
If you don't like the idea of having the client poll the server every now and then for aesthetic reasons (and I can appreciate that), for example you want the question to be refreshed at 16:00 on the dot, you could look into using a sockets. This, in effect, means the client is listening to any changes sent from the server, without the need to poll it, and updates when necessary.
Socket.io is easy to use, but not the simplest when it comes to interfacing with php. I don't know if you're familiar with Node.js but here's a small discussion some others had regarding sockets and php:
What is the best way to use websockets along with PHP and MySQL scripts?
Related
I have some PHP app. At the moment I am developing part where an user submits a request/form to the server via ajax (jQuery). Server will insert thousands of records in MySQL database that will probably take couple minutes (due to various calculations etc).
Question: Is there a way to track progress of updates on server side? I understand I can write some output once everything is finished. A workaround would be something like:
- store somewhere session ID plus progress details (example: processed 3k inserts out of 5k - maybe in some progress table in database
- have front end jQuery script requesting that information from the server every 10 seconds or so...
Any ideas? Please feel free to ask any question you may have. Thank you.
While I don't know the specifics of what you're doing server-side, a script that takes a "couple minutes" to execute likely involves several distinct steps. It might make sense to have the script execute one step at a time, return its result, and then get called again to execute the next step.
By using a process like this, you'll be able to track progress client-side. The caveat is that if the client closes the browser window or leaves the page with your ajax code, the remaining steps won't be executed.
I'm building a web app in Node/Express such that users can set a timer so that a certain task gets executed or repeated. My question is how can I set timer for many users with an event triggered after deadline. I don't want to handle this on the client side beacuse users can close the browser. A good example of this is services such as pingdom.com that allow you to set timer and send a ping every X minutes to your server. How can this be acheived?
I hope I don't get many negatives for asking this and I'm also not asking you guys to write me the code. I simply want to know a robust strategy to solve this problem.
Here is what I thought about:
Save the endtime in db and using a cron job check every second to see if the time is up (This is not really good in my opinion since the query and all calculations might take more than 1 second)
Somehow assign a variable to setInterval and store them in a global list
Your web app would have a more responsive UI and your backend would scale better if each client held its own timer. Closing the browser wouldn't be a problem.
Persist the endtime in a DB in your server for the specific question.
On the client side, retrieve the endtime from the server, and use JavaScript to create a timer that would alert the user their time has expired.
On the server side, have an additional check that rejects answers if the answer is being submitted past endtime to prevent clients from cheating.
So I'm using a Raspberry Pi 2 with a rfid scanner and wrote a script in python that logs people in and out of our attendance system, connects to our postgresql database and returns some data like how much overtime they have and whether their action was a login or logout.
This data is meant to be displayed on a very basic webpage (that is not even on a server or anything) that just serves as a graphical interface to display said data.
My problem is that I cannot figure out how to dynamically display that data that my python script returns on the webpage without having to refresh it. I'd like it to simply fade in the information, keep it there for a few seconds and then have it fade out again (at which point the system becomes available again to have someone else login or logout).
Currently I'm using BeautifulSoup4 to edit the Html File and Chrome with the extension "LivePage" to then automatically update the page which is obviously a horrible solution.
I'm hoping someone here can point me in the right direction as to how I can accoumplish this in a comprehensible and reasonably elegant way.
TL;DR: I want to display the results of my python script on my web page without having to refresh it.
you can make a html file and send XHR request to the primary one every x seconds .
setTimeout(function(){
$.get( "yourPrimaryFile.xyz", function( data ) {
$( "body" )
.append(data) // Mr.X
}) }, 3000);
I assume an more or less obvious solution like building a REST API with e.g. Flask and using some javascript framework (e.g. Angular or React) on the frontend is out of scope / too much?
Besides that I can only think of using 'plain' jquery or similar frameworks, which is more or less what you do currently.
I would recommend trying the flask/angular combination. A simple app (few API endpoints for login and out and a few checks) and a basic website with dynamic content is setup pretty quickly.
To update page data without delay you need to use websockets.
There is no need in using heavy frameworks.
Once page is loaded first time you open websocket with js and listen to it.
Every time you read a tag you post all necessary data to this open socket and it instantly appear on client side.
I was tasked to build a calendar and agenda library (I'm working on the CodeIgniter framework), that shows a calendar and the user has the possibility to set events on that calendar.
These events will have a notification system both email, and when the user is browsing the site, a popup.
My issue is how to approach the notification part when the user is on the site. The email is something that I already decided would be done trough a cronjob that will run every x minutes and check if there is any need to send a notification email.
The on site notification is something else.
How would I approach this? I just can't make a ajax request to the server every x seconds, since that would put an unnaceptable load on the system. (Of course when the user is eventually notified, a request must be made, to set the user as "remined" on the database).
I can't just depend on the user's date time, since he could be anywhere in the world and the time would be different.
How can I check that the user must be notified of a event, avoiding making repeated requests to the server? Would appreciate any input.
I could see using setTimeout to do this. Say a user visits your page $minutesTilDue minutes prior the reminder being due. Assuming jQuery/PHP:
$(function(){
setTimeout(function(){
showEventReminder(<?php json_encode($event) ?>);
}, <?php echo $minutesTilDue ?> * 60 * 1000);
});
Nothing too fancy, but depending on your requirements...
Cheers
Easily scalable notification systems use websockets, which today reach the majority of the users, even on mobile devices. Unfortunately, you'll need a websocket-enabled server - node, glassfish, whatever - this can't be done with standard PHP deployments (mod_php or fcgi). Server events (so called server push) are sent when they are generated, so once you have your websocket client-server pair, sending a reminder is just like sending an email.
Actually things are more complicated because most likely users won't be online at the exact time the reminder should pop up. I suggest a notification icon which is refreshed each time the user hits a page. This way your calendar system (suppose a cronjob) will simply update a flag for the user row in the DB, and when you build the page, you already know if there reminders (let's say, in the next 60 minutes) or not, and choose the icon accordingly. At this point, you have two choices:
sending the reminders to the client along with each and every request (it could be a waste of bandwidth, but I don't thing a JSON-encoded list of events is so heavyweight)
Download the reminders asynchronously on demand, ie only when the user hits the notification icon
This scenario lets you reuse the PHP environment and code, and doesn't require another host for the websocket server. I think this is the best solution, even if this doesn't fulfill your requirement of a truly popup reminder triggered by the server at the right time. BTW, if you send events with every request, your javascript can pop up when needed - you can use setTimeout() for this.
I'm building a basic little AJAX shoutbox/chat for my website, but I'm not sure exactly how to implement the server polling.
Here's the basic program flow I'm thinking of:
User comes to page and is shown the last 10 messages
To get messages sent by others, the client javascript would request a URL with a timestamp parameter (set to the value of the last message the client received)
The server returns all messages (up to a max of 10) since that timestamp.
The only issue is how often to poll the server. Obviously it should poll each time a new message is added, but when you're just reading others' messages it needs to automatically update.
Should it be a set time limit? eg: every 10 seconds. Or, should it vary depending on usage? eg: Check after 5 seconds. If there's no messages, don't check for another 10 seconds. If there's still no new messages, check in 15 seconds, then 20, up to maybe once every 30 seconds max. Each time there's a new message detected reset your timer back down to 5 seconds and start again.
I'm just concerned about putting unnecessary stress on the server, considering that we could have hundreds of users concurrently online.
...or have I got the whole thing wrong? Is there a better way to implement a basic javascript chat?
You might want to look into what are known as Comet programming techniques to stream information down to your users, rather than having the client poll the server. This is actually a family of techniques, some of which may work better than others depending on the circumstances, such as what kind of server you're using and what kind of client compatibility you need.
If your server can handle a large number of open connections at a time (as in, it does not use an entire thread or process per connection, such as nginx or an erlang based server), you may wish to use a long polling technique, where as soon one message is received, the client immediately requests another message. If there are no messages available, the server simply keeps the connection open, possibly sending occasionally dummy data as a keepalive, until a message becomes available.
Comet, described by Brian is a nice technique, but requires session support on the server, which is probably more advanced than you care to implement for a simple chat box.
The best way to implement polling intervals is to imagine you having a chat window which you can minimize to do other stuff, or open to see if you have new messages. When you are in the middle of a conversation, you'll switch to it (poll) frequently. If you don't get any messages for a while, you will start looking rarer and rarer until you only check it occasionally.
Assuming you don't need to do real-time typing, you can probably poll every 3 seconds or so when at peak activity, and if nothing shows up for 5-10 polls, start to crank the interval up (perhaps doubling it every time) until it hits 30-60 seconds. Getting a message back should reset the poll interval back to a few seconds, while sending a message should poll instantly, but probably doesn't need to effect the frequency of polling otherwise.
Honestly, if you are implementing a “basic little AJAX shoutbox/chat”, things like Jabber, Comet etc are overkill for you. These things will require you to run additional
servers/proxies to take the load of the app server and db.
When you think about stuff like presence management (“Joe is typing...”), then things get overly complex for your app (considering “chat” is not your prime focus).
Think about adding widgets from providers like Meebo and Userplane. Once you scale think about the Jabber and the like…
You should check to see if the other user is typing every 5 seconds or so, if the other user is typing, then you can check every 1 second to see if the user has sent a new message. Really though, you should be able to check every 1 second to see if other user is typing and if they are then every .25-.5 second check to see if new message has been sent. With broadband being so generally accepted on the inet, shouldn't be a problem. Go with the longer poll timeout for a dial-up access.
This is a very hard question, keep abuse in mind. Malicious users will hit you as often as possible, with the earliest timestamp faked so as to cause stress on your DB server. Be sure to validate that timestamp, or ignore it, because shouldnt everyone be in the same time anyway?
You can send the polling interval to the user as a function of the other user's response time. That's the best kind of dynamic I think.
http://jabbify.com/home/comet_service
This is a free comet based chat service by the guys who did the jmvc framework. Haven't tried it yet, but looks promising.
The professional way of doing this is with a WebSocket javascript connection. You can use a free service like https://socketsbay.com/ for example, and connect using
// Create WebSocket connection.
const socket = new WebSocket('wss://socketsbay.com/wss/v2/[ChannelId]/[ApiKey]/');
// Connection opened
socket.addEventListener('open', function (event) {
socket.send('Hello Server!');
});
// Listen for messages
socket.addEventListener('message', function (event) {
console.log('Message from server ', event.data);
});
You can forget about server pooling time because it will be realtime.