How to schedule a periodic task in Java?

前端 未结 11 1829
星月不相逢
星月不相逢 2020-11-22 08:51

I need to schedule a task to run in at fixed interval of time. How can I do this with support of long intervals (for example on each 8 hours)?

I\'m currently using <

11条回答
  •  再見小時候
    2020-11-22 09:07

    Try this way ->

    Firstly create a class TimeTask that run your task, it looks like:

    public class CustomTask extends TimerTask  {
    
       public CustomTask(){
    
         //Constructor
    
       }
    
       public void run() {
           try {
    
             // Your task process
    
           } catch (Exception ex) {
               System.out.println("error running thread " + ex.getMessage());
           }
        }
    }
    

    then in main class you instantiate the task and run it periodically started by a specified date:

     public void runTask() {
    
            Calendar calendar = Calendar.getInstance();
            calendar.set(
               Calendar.DAY_OF_WEEK,
               Calendar.MONDAY
            );
            calendar.set(Calendar.HOUR_OF_DAY, 15);
            calendar.set(Calendar.MINUTE, 40);
            calendar.set(Calendar.SECOND, 0);
            calendar.set(Calendar.MILLISECOND, 0);
    
    
    
            Timer time = new Timer(); // Instantiate Timer Object
    
            // Start running the task on Monday at 15:40:00, period is set to 8 hours
            // if you want to run the task immediately, set the 2nd parameter to 0
            time.schedule(new CustomTask(), calendar.getTime(), TimeUnit.HOURS.toMillis(8));
    }
    

提交回复
热议问题