Suppose there is a list of hours with minutes: [15.15, 18.30, 00.45] , etc. You need to perform some Runnable in a java application when “on the clock” is one of the time periods from the list above. How best to implement this? Preferably without using third-party libraries.

I tried to do it like this: Pathetic attempt

But it does not work.

  • one
    Create a timer with a response interval of 1 minute and check whether the time has come. - Oleksiy Morenets
  • I added a try, can you see? - Prototype - TV

1 answer 1

I use the normal java.time library

 public static void main(String[] args) { LocalDateTime ldt = LocalDateTime.now().plusMinutes(1); Timer timer = new Timer(); timer.schedule(new TimerTask() { @Override public void run() { System.out.println("run"); timer.cancel(); } }, Date.from(ldt.atZone(ZoneId.systemDefault()).toInstant())); } 
  • Although it should work through the calendar too ... - Oleksiy Mororets
  • The question is why after the execution of "run" the application does not shut down? - Prototype - TV
  • Because the timer is in the stream, and no one has completed it. - Olexiy Morenets
  • I added cancel after "run" .sout but nothing has changed. - Prototype - TV
  • one
    Everything, the question is solved. I just called cancel () in "run" for Task, but I had timer.cancel (); - Prototype - TV