Running a Java method at a set time each day

后端 未结 3 1793
不知归路
不知归路 2020-12-30 02:54

I\'m relatively new to Java and I\'ve pick up a project to work on. However, I\'ve run into a block. I need a method to run at a certain times throughout the day. I\'ve d

3条回答
  •  失恋的感觉
    2020-12-30 03:34

    try the TimerTask class

    for more info check out http://oreilly.com/java/archive/quartz.html

    import java.util.Calendar;
    import java.util.Date;
    import java.util.Timer;
    import java.util.TimerTask;
    
    public class ReportGenerator extends TimerTask {
    
      public void run() {
        System.out.println("Generating report");
        //TODO generate report
      }
    
    }
    
    class MainApplication {
    
      public static void main(String[] args) {
        Timer timer = new Timer();
        Calendar date = Calendar.getInstance();
        date.set(
          Calendar.DAY_OF_WEEK,
          Calendar.SUNDAY
        );
        date.set(Calendar.HOUR, 0);
        date.set(Calendar.MINUTE, 0);
        date.set(Calendar.SECOND, 0);
        date.set(Calendar.MILLISECOND, 0);
        // Schedule to run every Sunday in midnight
        timer.schedule(
          new ReportGenerator(),
          date.getTime(),
          1000 * 60 * 60 * 24 * 7
        );
      }//Main method ends
    }//MainApplication ends
    

提交回复
热议问题