How to schedule a periodic task in Java?

前端 未结 11 1788
星月不相逢
星月不相逢 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:17

    These two classes can work together to schedule a periodic task:

    Scheduled Task

    import java.util.TimerTask;
    import java.util.Date;
    
    // Create a class extending TimerTask
    public class ScheduledTask extends TimerTask {
        Date now; 
        public void run() {
            // Write code here that you want to execute periodically.
            now = new Date();                      // initialize date
            System.out.println("Time is :" + now); // Display current time
        }
    }
    

    Run Scheduled Task

    import java.util.Timer;
    
    public class SchedulerMain {
        public static void main(String args[]) throws InterruptedException {
            Timer time = new Timer();               // Instantiate Timer Object
            ScheduledTask st = new ScheduledTask(); // Instantiate SheduledTask class
            time.schedule(st, 0, 1000);             // Create task repeating every 1 sec
            //for demo only.
            for (int i = 0; i <= 5; i++) {
                System.out.println("Execution in Main Thread...." + i);
                Thread.sleep(2000);
                if (i == 5) {
                    System.out.println("Application Terminates");
                    System.exit(0);
                }
            }
        }
    }
    

    Reference https://www.mkyong.com/java/how-to-run-a-task-periodically-in-java/

提交回复
热议问题