How to schedule a periodic task in Java?

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

    Use Google Guava AbstractScheduledService as given below:

    public class ScheduledExecutor extends AbstractScheduledService {
    
       @Override
       protected void runOneIteration() throws Exception {
          System.out.println("Executing....");
       }
    
       @Override
       protected Scheduler scheduler() {
            return Scheduler.newFixedRateSchedule(0, 3, TimeUnit.SECONDS);
       }
    
       @Override
       protected void startUp() {
           System.out.println("StartUp Activity....");
       }
    
    
       @Override
       protected void shutDown() {
           System.out.println("Shutdown Activity...");
       }
    
       public static void main(String[] args) throws InterruptedException {
           ScheduledExecutor se = new ScheduledExecutor();
           se.startAsync();
           Thread.sleep(15000);
           se.stopAsync();
       }
    }
    

    If you have more services like this, then registering all services in ServiceManager will be good as all services can be started and stopped together. Read here for more on ServiceManager.

提交回复
热议问题