Przeglądaj źródła

Server: Timer thread safety - don't schedule already scheduled subscribers when next loop comes too early

Christian Kahlau 3 lat temu
rodzic
commit
3e3c06d5a0
1 zmienionych plików z 4 dodań i 1 usunięć
  1. 4 1
      server/src/timer.class.ts

+ 4 - 1
server/src/timer.class.ts

@@ -2,6 +2,7 @@ type Subscriber = {
   lastTick: number;
   seconds: number;
   tick: (() => void) | Promise<void>;
+  queued?: boolean;
 };
 
 export class Timer {
@@ -31,7 +32,8 @@ export class Timer {
   private loop() {
     const now = new Date();
     Object.values(this.subscribers).forEach(sub => {
-      if (now.getTime() >= sub.lastTick + sub.seconds * 1000) {
+      if (!sub.queued && now.getTime() >= sub.lastTick + sub.seconds * 1000) {
+        sub.queued = true;
         this.queue.push(sub);
       }
     });
@@ -48,6 +50,7 @@ export class Timer {
       } else {
         await sub.tick;
       }
+      sub.queued = false;
     }
   }