简体   繁体   中英

How to execute an emit (socket.io) at a specific time with NodeJS?

I have an android application which communicates with the NodeJS server through socket.io.

I need my NodeJS server to send an emit at a specific time like 7 o'clock to all clients.

Example:

socket.emit ('example', 'data', 'hour to emit');

Thanks for your help !

If you want to do it once at a static time you know, then just use setTimeout and calculate the difference between the server's current time and the emit time and pass it to setTimeout call.

If you want to do it more than once at static times you know, you can store these times in an array an then use setInterval with an interval of 1 minute to check if it's time to execute an emit.

The implementation totally depends on your needs. Maybe you need to store execution times in a database and then make a REST api to check for them and configure a cronjob to call this api each minute.

I did a little research and apparently setTimeout or setInterval are resource intensive. Finally, I opted for CRON at the desired time which makes an HTTP call in GET. Thank's!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM