How to schedule a periodic task in Java?

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

    I use Spring Framework's feature. (spring-context jar or maven dependency).

    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.beans.factory.annotation.Qualifier;
    import org.springframework.scheduling.annotation.Scheduled;
    import org.springframework.stereotype.Component;
    
    
    @Component
    public class ScheduledTaskRunner {
    
        @Autowired
        @Qualifier("TempFilesCleanerExecution")
        private ScheduledTask tempDataCleanerExecution;
    
        @Scheduled(fixedDelay = TempFilesCleanerExecution.INTERVAL_TO_RUN_TMP_CLEAN_MS /* 1000 */)
        public void performCleanTempData() {
            tempDataCleanerExecution.execute();
        }
    
    }
    

    ScheduledTask is my own interface with my custom method execute, which I call as my scheduled task.

    0 讨论(0)
  • 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/

    0 讨论(0)
  • 2020-11-22 09:17

    Have you tried Spring Scheduler using annotations ?

    @Scheduled(cron = "0 0 0/8 ? * * *")
    public void scheduledMethodNoReturnValue(){
        //body can be another method call which returns some value.
    }
    

    you can do this with xml as well.

     <task:scheduled-tasks>
       <task:scheduled ref = "reference" method = "methodName" cron = "<cron expression here> -or- ${<cron expression from property files>}"
     <task:scheduled-tasks>
    
    0 讨论(0)
  • 2020-11-22 09:21

    Use a ScheduledExecutorService:

     private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
     scheduler.scheduleAtFixedRate(yourRunnable, 8, 8, TimeUnit.HOURS);
    
    0 讨论(0)
  • 2020-11-22 09:26

    If your application is already using Spring framework, you have Scheduling built in

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