[英]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.我有一个 android 应用程序,它通过 socket.io 与 NodeJS 服务器通信。
I need my NodeJS server to send an emit at a specific time like 7 o'clock to all clients.我需要我的 NodeJS 服务器在特定时间(例如 7 点)向所有客户端发送发射。
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.如果您想在您知道的 static 时间执行一次,则只需使用setTimeout
并计算服务器当前时间与发出时间之间的差并将其传递给setTimeout
调用。
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.如果你想在你知道的 static 次多次执行此操作,则可以将这些时间存储在一个数组中,然后使用setInterval
以 1 分钟的时间间隔检查是否是执行发射的时间。
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.也许您需要将执行时间存储在数据库中,然后创建 REST api 来检查它们并配置一个 cronjob 以每分钟调用此 api。
I did a little research and apparently setTimeout or setInterval are resource intensive.我做了一些研究,显然 setTimeout 或 setInterval 是资源密集型的。 Finally, I opted for CRON at the desired time which makes an HTTP call in GET.最后,我在所需的时间选择了 CRON,它在 GET 中调用了 HTTP。 Thank's!谢谢!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.