19
Nov

Execute a java code at specific time with ScheduledExecutorService

Execute a java code at specifictime with ScheduledExecutorService

		final LocalDateTime now = LocalDateTime.now();
		final LocalDateTime ninePMToday = LocalDateTime.now().withHour(10).withMinute(18).withSecond(15).withNano(0);
		final ScheduledExecutorService ses = Executors.newScheduledThreadPool(1);
		ses.schedule(() -> System.out.println("It's 9pm!"), now.until(ninePMToday, ChronoUnit.MILLIS),
				TimeUnit.MILLISECONDS);
		
		ses.shutdown();
You can also schedule it to repeatedly execute at 9pm every day with a small tweak to the scheduler call:

ses.scheduleAtFixedRate(() -> System.out.println("It's 9pm!"),
                        now.until(ninePMToday, ChronoUnit.MILLIS),
                        TimeUnit.DAYS.toMillis(1),
                        TimeUnit.MILLISECONDS);