Fix periodic broadcasts by using proper message passing from the worker.

In this way, no need to pass all the context that methods need to work to the worker.
This commit is contained in:
Matthew Raymer
2023-08-17 16:56:40 +08:00
parent 5b689125a6
commit 684d7f1791
3 changed files with 12 additions and 11 deletions

View File

@@ -1,4 +1,4 @@
// Subscription.ts
// VapidKeys.ts
import { Entity, PrimaryGeneratedColumn, Column } from 'typeorm';
@Entity()

View File

@@ -1,8 +1,10 @@
import { SubscriptionService } from './subscriptionService.js';
import { Message, NotificationService } from './notificationService.js';
import express, { Express, Request, Response } from 'express';
import { Worker } from 'worker_threads';
import { fileURLToPath } from 'url';
import { dirname, join } from 'path';
import { networkInterfaces } from 'os';
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
@@ -20,11 +22,14 @@ class Server {
private port: number;
private worker?: Worker;
private subscriptionService: SubscriptionService;
private notificationService: NotificationService;
private message: Message;
constructor(port: number) {
this.app = express();
this.port = port;
this.subscriptionService = new SubscriptionService();
this.notificationService = new NotificationService();
this.setupRoutes();
this.startWorker();
@@ -46,7 +51,9 @@ class Server {
this.worker = new Worker(workerPath, { workerData: 'world' });
this.worker.on('message', (message) => {
console.log(`Received message from worker: ${message}`);
console.log(`Received message from worker: ${message} @ ${new Date()}`);
this.message = { "title": "Check TimeSafari"} as Message;
this.notificationService.broadcast(this.message);
});
this.worker.on('error', (error) => {
@@ -80,5 +87,6 @@ class Server {
}
// Initialize and start the server
const server = new Server(3000);
server.start();

View File

@@ -1,27 +1,20 @@
import { parentPort } from 'worker_threads';
import { Message, NotificationService } from './notificationService.js'
class WorkerThread {
private interval: number;
private notificationService: NotificationService;
private message: Message;
constructor(interval: number) {
this.interval = interval;
this.notificationService = new NotificationService();
this.message = { "title": "Check the app." };
this.startPeriodicTask();
}
private startPeriodicTask(): void {
setInterval(() => {
if (parentPort) {
this.notificationService.broadcast(this.message);
parentPort.postMessage("send notifications")
}
}, this.interval);
}
}
new WorkerThread(3600 * 24); // pole once per day
new WorkerThread(24*3600*1000); // pole once per day