How i can run my TimerTask everyday 2 PM

后端 未结 9 1651
说谎
说谎 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);
    
        }  
    
    0 讨论(0)
  • 2020-12-01 03:21

    Why don't you use Spring's @Scheduled(cron="0 0 14 * * *") .. for sec, min, hours, day, month, dayOfWeek. V Cool. You can even specify 9-11 for 9:00 to 11:00, or MON-FRI in last parameter. You can invoke this programatically too, like is case of most of Spring, in case you want to set the time at runtime. See this:- http://docs.spring.io/spring/docs/current/spring-framework-reference/html/scheduling.html

    Adding an example

       @Scheduled(cron="0 0 14 * * *")
        public void customScheduler(){
            try{
                // do what ever you want to run repeatedly
            }catch(Exception e){
                e.printStackTrace();
    
            }
        }
    

    also please annotate the class containing this with @Component annotation and please provide @EnableScheduling in the Application.java (class contains the main method) class to make spring aware that you are using taskscheduler in your applicaiton.

    0 讨论(0)
  • 2020-12-01 03:24
    Calendar today = Calendar.getInstance();
    today.set(Calendar.HOUR_OF_DAY, 2);
    today.set(Calendar.MINUTE, 0);
    today.set(Calendar.SECOND, 0);
    
    // every night at 2am you run your task
    Timer timer = new Timer();
    timer.schedule(new YourTask(), today.getTime(), TimeUnit.MILLISECONDS.convert(1, TimeUnit.DAYS)); // period: 1 day
    
    0 讨论(0)
  • 2020-12-01 03:27

    The easiest way I've found of doing this has always been through Task Scheduler in Windows and cron in Linux.

    However for Java, take a look at Quartz Scheduler

    From their website:

    Quartz is a full-featured, open source job scheduling service that can be integrated with, or used along side virtually any Java EE or Java SE application - from the smallest stand-alone application to the largest e-commerce system. Quartz can be used to create simple or complex schedules for executing tens, hundreds, or even tens-of-thousands of jobs; jobs whose tasks are defined as standard Java components that may execute virtually anything you may program them to do. The Quartz Scheduler includes many enterprise-class features, such as JTA transactions and clustering.

    0 讨论(0)
  • 2020-12-01 03:29
    import java.util.Calendar;
    import java.util.Date;
    import java.util.GregorianCalendar;
    import java.util.Timer;
    import java.util.TimerTask;
    
    
    public class MyTimerTask extends TimerTask {
        private final static long ONCE_PER_DAY = 1000*60*60*24;
    
        //private final static int ONE_DAY = 1;
        private final static int TWO_AM = 2;
        private final static int ZERO_MINUTES = 0;
    
    
        @Override
        public void run() {
            long currennTime = System.currentTimeMillis();
            long stopTime = currennTime + 2000;//provide the 2hrs time it should execute 1000*60*60*2
              while(stopTime != System.currentTimeMillis()){
                  // Do your Job Here
                System.out.println("Start Job"+stopTime);
                System.out.println("End Job"+System.currentTimeMillis());
              }
        }
        private static Date getTomorrowMorning2AM(){
    
            Date date2am = new java.util.Date(); 
               date2am.setHours(TWO_AM); 
               date2am.setMinutes(ZERO_MINUTES); 
    
               return date2am;
          }
        //call this method from your servlet init method
        public static void startTask(){
            MyTimerTask task = new MyTimerTask();
            Timer timer = new Timer();  
            timer.schedule(task,getTomorrowMorning2AM(),1000*10);// for your case u need to give 1000*60*60*24
        }
        public static void main(String args[]){
            startTask();
    
        }
    
    }
    
    0 讨论(0)
  • 2020-12-01 03:29

    Most answers for this question and the following two questions assume that the milliseconds per day is always the same.
    How to schedule a periodic task in Java?
    How to run certain task every day at a particular time using ScheduledExecutorService?

    However, it's not ture due to day lights saving and leap seconds. This means that if your service is alive for years and the accuracy of the timer matters, a fixed period timer is not your choice.

    So, I'd like to introduce my code snippet for a more flexible timer than the java.util.Timer.

    package szx;
        
    import java.time.LocalDateTime;
    import java.time.ZoneId;
    import java.util.Date;
    import java.util.Timer;
    import java.util.TimerTask;
    import java.util.function.Function;
        
    public class ScheduledExecutor {
      public void scheduleRegularly(Runnable task, LocalDateTime firstTime,
                                    Function<LocalDateTime, LocalDateTime> nextTime) {
        pendingTask = task;
        scheduleRegularly(firstTime, nextTime);
      }
    
      protected void scheduleRegularly(LocalDateTime firstTime,
                                       Function<LocalDateTime, LocalDateTime> nextTime) {
        new Timer().schedule(new TimerTask() {
          @Override
          public void run() {
            scheduleRegularly(nextTime.apply(firstTime), nextTime);
            pendingTask.run();
          }
        }, Date.from(firstTime.atZone(ZoneId.systemDefault()).toInstant()));
      }
    
      private volatile Runnable pendingTask = null;
    }
    

    Then, you can execute your job everyday 2PM by invoking the above method in the following way.

    new ScheduledExecutor().scheduleRegularly(() -> {
    
        // do your task...
    
    }, LocalDateTime.now().truncatedTo(ChronoUnit.DAYS).withHour(14), thisTime -> thisTime.plusDays(1));
    

    The basic idea behind the code is to recalculate the left time to the next tick and start a new timer every time.

    0 讨论(0)
提交回复
热议问题