0

I want to execute a task in every hour, but I found the Timer can only set period.

My Requirement is:

  1. When I start the timer, the task will be executed immediately.
  2. Run at each hour. If I start the program at 1:20, it will be executed at once. The next time to execute is 2:00. and the next is 3:00, and so on.
  3. If I start the program at 1:20, and the task does not finsihed at 2:00, The task of 2:00 will be delayed. When the task of 1:20 is finished, the task of 2:00 will be executed at once.

I think the Timer of JDK only provide the period between 2 tasks. If I start the program at 1:20, the second one only can be executed at 2:20, the third one only can be executed at 3:20. So I don't know how to implement a custom timer.

S.Lee
  • 206
  • 1
  • 4
  • 15
  • What have you done so far and what is the problem that you are facing. Have a look at following for hint. https://stackoverflow.com/questions/7814089/how-to-schedule-a-periodic-task-in-java – Jabir Nov 18 '20 at 06:47
  • I use Timer.schedule() method and set the period 1 hour. If task starts at 1:20, the next task will start at 2:20, not 2:00. the third one will start at 3:20 not 3:00. – S.Lee Nov 18 '20 at 08:16

1 Answers1

0

Following code will execute at start of every hour.

 Calendar calendar = Calendar.getInstance();
 ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
 scheduler.scheduleAtFixedRate(new YourTask(), millisToNextHour(calendar), 60*60*1000, TimeUnit.MILLISECONDS);

 private static long millisToNextHour(Calendar calendar) {
        int minutes = calendar.get(Calendar.MINUTE);
        int seconds = calendar.get(Calendar.SECOND);
        int millis = calendar.get(Calendar.MILLISECOND);
        int minutesToNextHour = 60 - minutes;
        int secondsToNextHour = 60 - seconds;
        int millisToNextHour = 1000 - millis;
        return minutesToNextHour*60*1000 + secondsToNextHour*1000 + millisToNextHour;
    }

For the first time you can do sth like new YourTask().start();or anyother way that suits to your requirements.

Jabir
  • 2,776
  • 1
  • 22
  • 31
  • If I start my task first time, but it is not finished in one hour, the second task will be executed immediately. It will not wait for the first one. Because they are not executed by one Timer. – S.Lee Nov 18 '20 at 12:06
  • That's why i requested to use whatever suits your requirements. – Jabir Nov 18 '20 at 12:08