package com.timostaudinger.dailydose.trigger;


import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

@WebListener
public class Trigger implements ServletContextListener {

    private ScheduledExecutorService scheduler;

    @Override
    public void contextInitialized(ServletContextEvent event) {
        LocalDateTime localNow = LocalDateTime.now();
        ZoneId currentZone = ZoneId.of("America/New_York");
        ZonedDateTime zonedNow = ZonedDateTime.of(localNow, currentZone);
        ZonedDateTime zonedExecutionTime;
        zonedExecutionTime = zonedNow.withHour(8).withMinute(0).withSecond(0);
        if (zonedNow.compareTo(zonedExecutionTime) > 0)
            zonedExecutionTime = zonedExecutionTime.plusDays(1);

        Duration duration = Duration.between(zonedNow, zonedExecutionTime);
        long initalDelay = duration.getSeconds();

        scheduler = Executors.newSingleThreadScheduledExecutor();
        scheduler.scheduleAtFixedRate(new DailyRunner(), initalDelay,
                24 * 60 * 60, TimeUnit.SECONDS);
    }

    @Override
    public void contextDestroyed(ServletContextEvent event) {
        scheduler.shutdownNow();
    }

}

@@ -611,32 +611,314 @@
 tEvent event) %7B%0A
+        long initalDelay = getSecondsUntil9Am();%0A%0A        scheduler = Executors.newSingleThreadScheduledExecutor();%0A        scheduler.scheduleAtFixedRate(new DailyRunner(), initalDelay,%0A                24 * 60 * 60, TimeUnit.SECONDS);%0A    %7D%0A%0A    private long getSecondsUntil9Am() %7B%0A
         LocalDat
@@ -1416,34 +1416,22 @@
         
-long initalDelay =
+return
  duratio
@@ -1449,194 +1449,8 @@
 s();
-%0A%0A        scheduler = Executors.newSingleThreadScheduledExecutor();%0A        scheduler.scheduleAtFixedRate(new DailyRunner(), initalDelay,%0A                24 * 60 * 60, TimeUnit.SECONDS);
 %0A   

Refactor Trigger class