I want to execute a job everyday 2PM .
Which method of java.util.Timer i can use to schedule my job?
After 2Hrs Run it will stop the job and reschedule
Due java.util.Timer:
Java 5.0 introduced the java.util.concurrent package and one of the concurrency utilities therein is the ScheduledThreadPoolExecutor which is a thread pool for repeatedly executing tasks at a given rate or delay. It is effectively a more versatile replacement for the Timer/TimerTask combination, as it allows multiple service threads, accepts various time units, and doesn't require subclassing TimerTask (just implement Runnable). Configuring ScheduledThreadPoolExecutor with one thread makes it equivalent to Timer.
so (add this code to your class):
private ScheduledExecutorService scheduledExecutorService;
public ScheduledSendLog() {
init();
}
public void destroy() {
this.scheduledExecutorService.shutdown();
}
private void init() {
scheduledExecutorService =
Executors.newScheduledThreadPool(1);
System.out.println("---ScheduledSendLog created " + LocalDateTime.now());
startSchedule(LocalTime.of(02, 00));
}
private void startSchedule(LocalTime atTime) {
this.scheduledExecutorService.scheduleWithFixedDelay(() -> {
System.out.println(Thread.currentThread().getName() +
" | scheduleWithFixedDelay | " + LocalDateTime.now());
// or whatever you want
}, calculateInitialDelayInSec(atTime),
LocalTime.MAX.toSecondOfDay(),
TimeUnit.SECONDS);
}
private long calculateInitialDelayInSec(LocalTime atTime) {
int currSec = LocalTime.now().toSecondOfDay();
int atSec = atTime.toSecondOfDay();
return (currSec < atSec) ?
atSec - currSec : (LocalTime.MAX.toSecondOfDay() + atSec - currSec);
}