Benachrichtigungen für Benutzerereignisse als Zeitstempel in DB gespeichertJava

Java-Forum
Anonymous
 Benachrichtigungen für Benutzerereignisse als Zeitstempel in DB gespeichert

Post by Anonymous »

Benutzer können Ereigniszeitstempel planen, bei denen sie später benachrichtigt werden sollten:
Ereignisse

Code: Select all

id | name | epochms
< /code>
Im Moment habe ich einen Controller zum Erstellen eines Ereignisses und gleich nach dem Erstellen plant es wie folgt: < /p>
@PostMapping("new_event")
public void newEvent(@RequestBody EventDto eventDto) {
service.createEvent(eventDto);
}
< /code>
public void createEvent(EventDto eventDto) {
Event event = converter.convert(eventDto);
event = repository.save(event);
scheduler.schedule(event);
}
< /code>
protected final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(50);

public void schedule(Event event) {
long delay = event.getTimestamp() / 1_000L - Instant.now().getEpochSecond();
scheduler.schedule(() -> notify(event), delay, TimeUnit.SECONDS);
}

@Transactional
public void notify(Event event) {
// notify the user, save changes in db
}
< /code>
Currently it works well, but only with a handful of users. I realize that it's not very efficient and if there are more users I wouldn't be able to create a separate thread per user event.
I'm trying to figure out what are the better approaches that are usually used in cases like this.
One approach I see is to use virtual threads: thousands of them could be created, and a custom scheduler could be used, like in the linked article:
static Future schedule(Runnable task, int delay, TemporalUnit unit, ExecutorService executorService) {
return executorService.submit(() -> {
try {
Thread.sleep(Duration.of(delay, unit));
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}

task.run();
});
}
< /code>
I'm not sure it's the correct approach, though. Another one I've been thinking about is having a PriorityQueue
der ausstehenden Ereignisse, zum Beispiel alle Ereignisse in der nächsten Stunde und eine einzelne Thread -Abfrage, die jede Sekunde an der Schlange steht, um zu sehen, ob es dort neue Ereignisse gibt. Ich bin mir jedoch nicht sicher, wie gut es skalieren würde.>

Quick Reply

Change Text Case: 
   
  • Similar Topics
    Replies
    Views
    Last post