id | name | epochms
< /code>
Прямо сейчас у меня есть контроллер для создания события, и сразу после его создания он планирует его так: < /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
ожидающих событий, например, все события в следующем часе и имеют один запрос потока, который встает в очередь каждую секунду, чтобы увидеть, есть ли там какие -либо новые события. Я не уверен, насколько хорошо это масштабируется.>
Пользователи могут запланировать временные метки событий, при которых они должны быть уведомлены: [b] События [/b] [code]id | name | epochms < /code> Прямо сейчас у меня есть контроллер для создания события, и сразу после его создания он планирует его так: < /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[/code] ожидающих событий, например, все события в следующем часе и имеют один запрос потока, который встает в очередь каждую секунду, чтобы увидеть, есть ли там какие -либо новые события. Я не уверен, насколько хорошо это масштабируется.>
Я пишу веб-приложение для совместной работы в команде на PHP, и у меня есть несколько событий, о которых пользователи уведомляются по электронной почте и/или SMS. Сейчас я делаю это следующим образом:
Spring Boot настаивает на сериализации моих данных ZonedDateTime типа в виде временной метки с плавающей точкой за несколько секунд. Я пробовал все методы в Интернете, но ни один из них не мог заставить его сдаться.
точнее, контроллер REST всегда...