我必须在 nodejs 中创建一个定时应用程序,用户可以设置每天、每周和每月。我的第一个任务是创建这样的东西:
socket.on("connect")
{
client.on("authenticate")
{
var frequency = GetTimersForUser(client);
var timersInMilliseconds = ConvertFrequencyToMS(frequency);
var nextInMS = GetLower(timersInMilliseconds);
setTimeout("timedCount()",nextInMS );
}
}
timedCount()
{
cancelTimer;
client.emit("poke");
var frequency = GetTimersForUsers(client);
...
setTimeout("timedCount()",nextInMS );
}
但这不会提醒我有关失败的计时器(如果客户端已断开连接),因为计时器仅在连接后创建,所以我想在连接之前创建计时器。那么,每秒创建 1 个计时器是否更快:
userslist = getIndividualUsersNextTimerAsDate();
setTimout("timedCount()",1000);
timedCount()
{
foreach(user in userslist)
{
if(user.time <= now())
{
if(user.socket)
{
user.socket.emit("poke");
}
user.time = resetTimeForNextTimer(user);
}
}
}
socket.on("connect")
{
...
userslist[x].socket = client;
}
或每个“时间”多个计时器:
var userslist = GetUsersTimers();
foreach(user in userslist)
{
user.Counter = setTimeout("runTime()",client.timer );
}
runTime(client)
{
client.emit("poke");
client.Counter.cancel();
client.timer = resetToNextTimer();
client.Counter = setTimeout("runTime()",client.timer );
}
还是有什么更好的方法让我想念?