| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586 |
- package cz.senslog.watchdog.util.schedule;
- import cz.senslog.watchdog.messagebroker.email.EmailMessageBroker;
- import org.apache.logging.log4j.LogManager;
- import org.apache.logging.log4j.Logger;
- import java.time.LocalDateTime;
- import java.time.temporal.ChronoUnit;
- import java.util.concurrent.CountDownLatch;
- import java.util.concurrent.ScheduledExecutorService;
- import java.util.concurrent.ScheduledFuture;
- import static cz.senslog.watchdog.util.TimeConverter.secToMillis;
- import static java.util.concurrent.TimeUnit.MILLISECONDS;
- public final class ScheduleTask {
- private static final Logger logger = LogManager.getLogger(EmailMessageBroker.class);
- private static final int DEFAULT_DELAY_MILLIS = 2_000; // 2s
- private TaskDescription description;
- private final Runnable task;
- private final long periodMillis;
- private final LocalDateTime startAt;
- private final long delayMillis;
- private ScheduleTask(String name, Runnable task, long periodSec, LocalDateTime startAt, long delaySec) {
- this.description = new TaskDescription(name, Status.STOPPED);
- this.task = task;
- this.periodMillis = secToMillis(periodSec);
- this.startAt = startAt;
- this.delayMillis = secToMillis(delaySec);
- }
- public ScheduleTask(String name, Runnable task, long periodSec, LocalDateTime startAt) {
- this(name, task, periodSec, startAt, -1);
- }
- public ScheduleTask(String name, Runnable task, long periodSec, int delaySec) {
- this(name, task, periodSec, null, delaySec);
- }
- public ScheduleTask(String name, Runnable task, long periodSec) {
- this(name, task, periodSec, null);
- }
- public TaskDescription getDescription() {
- return description;
- }
- public Runnable getTask() {
- return task;
- }
- public long getPeriodMillis() {
- return periodMillis;
- }
- public void schedule(ScheduledExecutorService scheduledService, CountDownLatch latch) {
- long delay = DEFAULT_DELAY_MILLIS;
- if (startAt != null) {
- delay = LocalDateTime.now().until(startAt, ChronoUnit.MILLIS);
- } else if (delayMillis > 0) {
- delay = delayMillis;
- }
- logger.info("The task '{}' is going to be executed in {} ms.", description.getName(), delay);
- ScheduledFuture<?> future = scheduledService.scheduleAtFixedRate(task, delay, periodMillis, MILLISECONDS);
- description = new TaskDescription(description.getName(), Status.RUNNING);
- new Thread(() -> {
- try {
- future.get();
- } catch (Exception e) {
- e.printStackTrace();
- } finally {
- future.cancel(true);
- latch.countDown();
- description = new TaskDescription(description.getName(), Status.STOPPED);
- }
- }, "thread-" + description.getName()).start();
- }
- }
|