I try to excute the code every hour
This is for java in applicationRunner that can be run with the server is started.
@Component
public class TestApplicationRunner implements ApplicationRunner {
// some Autowired
@Override
public void run(ApplicationArguments args) throws Exception {
TimerTask repeatedTask = new TimerTask() {
@Override
public void run() {
System.out.println("Task performed on " + new Date()); //now
//Some code that updates the database
}
};
Timer timer = new Timer();
Calendar date = Calendar.getInstance();
LocalDateTime nextHour = LocalDateTime.now().plusHours(1).truncatedTo(ChronoUnit.HOURS);
long result = LocalDateTime.now().until(nextHour, ChronoUnit.MILLIS);
System.out.println(date.getTime());
long period = 1000L * 60L * 60L;
timer.scheduleAtFixedRate(repeatedTask, result, period);
}
}
if I run this code at 12:34, the result is
Task performed on 13 : 00
Task performed on 14 : 00
Task performed on 14 : 00
Task performed on 15 : 00
Task performed on 15 : 00
Task performed on 15 : 00
Task performed on 16 : 00
Task performed on 16 : 00
Task performed on 16 : 00
Task performed on 16 : 00
.....
I want to receive
Task performed on 13 : 00
Task performed on 14 : 00
Task performed on 15 : 00
Task performed on 16 : 00
Task performed on 17 : 00
.....
I think there are more thread than one, but I can't understand why they have several thread. I add my code. thank you for help