How i can run my TimerTask everyday 2 PM

后端 未结 9 1676
说谎
说谎 2020-12-01 02:48

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

9条回答
  •  再見小時候
    2020-12-01 03:16

    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);
    
        }  
    

提交回复
热议问题