Reputation: 929
I have a Node
server that is using socket.io
. I would like my socket
object to emit some data to the connected browser once per minute on the minute. Ideally something like setInterval()
but instead of calling every x minutes, look at the time and execute at on the minute.
I imagine it would look something like this, if I wanted to send every 1 minutes.
var data = "someData";
io.on('connection', function (socket) {
socket.emit_every_x_minutes(1, 'myData', data)}
});
This would emit "someData"
to the client socket periodically every 1 minute.
What is the correct way to emit every x minutes socket.io
?
Upvotes: 4
Views: 6618
Reputation: 890
You can use node-schedule or node-cron modules.
Visit : https://www.npmjs.com/package/node-schedule
or
Visit: http://merencia.com/node-cron/
Upvotes: 1
Reputation: 3444
Why not use setInterval / setTimeout ?
var data = "someData";
io.on('connection', (socket) => {
setInterval(() => {
socket.emit(1, 'myData', data)}
}, 60 * 1000);
});
If you want on the minute, every minute, without a library:
var data = "someData";
const doEveryMinute = (socket) => {
setTimeout(() => {
setInterval(() => doEveryMinute(socket), 60000);
socket.emit(1, 'myData', data)}
}, (60 - date.getSeconds()) * 1000);
}
io.on('connection', (socket) => {
doEveryMinute(socket);
});
If accuracy is important, then you'll want something like https://github.com/kelektiv/node-cron.
Upvotes: 5