Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to synchronize backend timer with mobile app

I am developing a app that chooses a user and has a 15 sec. timer for that user to respond. The user app queries the db every 5 sec to see if that user is chosen. If so The mobile app begins a 15 sec. timer. The problem is that the timers will never match up because the user app can be on a different timer cycle that the backend and can query the db at a later time. I use Angular, NodeJS, and expressJS + MongoDB to develop this app.

any suggestion on how I can get the timers to be synchronized?

like image 480
Shawn Varughese Avatar asked Dec 15 '22 00:12

Shawn Varughese


2 Answers

You don't need to have two timers running at the same time. Start a timer on the front-end, then let the back-end know when the timer on the front-end started. As long as you treat one side as the single source of truth, the other side will be able to infer whether the timer has finished or not.

Although the timers might not be synchronized, time should be the same everywhere. If the back-end knows that the front-end timer started at 12:01:00, it also knows that the timer will end at 12:01:15. In this way, it can just continue to check whether the current time is before or after 12:01:15.

like image 87
vanev_ Avatar answered Dec 28 '22 11:12

vanev_


This is definitely a job for websockets! Websockets unlike HTTP enable two way data flow so your server and client can talk in real-time. Socket.io is a really popular framework for enabling this type of interaction and hooks really seamlessly into node/express.

http://socket.io/

Here is a tutorial to get your started http://socket.io/get-started/chat/.

The basic flow will be

  1. Open a socket between the user and the server.
  2. When the user is chosen (I assume on the server-side) then do a io.emit('user chosen', { userId: '<the user id>' });. This will send a message over the socket to all attached applications.
  3. Start the timer on the server and send info that the period is over. Something like this should work. setTimeout(() => socket.emit('user chosen end', { userId: '<the user id>' }), 15000);
  4. In your app you will be listening for the 'user_chosen' event and can check if the logged in user has the same id as the one sent over the socket. If the user id's match enable the text input for the user to set the input. Something like this: socket.on('user chosen', function(msg){ /* Enable the input */ });
  5. The app will also be listening for the 'user_chosen_end' event and if the ids of the user again match, disable the text input or do whatever else you need to do. Again this will look like: socket.on('user chosen end', function(msg){ /* Disable the input & do anything else */ });

Hope this helps :)

like image 20
mparis Avatar answered Dec 28 '22 11:12

mparis