How to stop a scheduled task that was started using @Scheduled annotation?

后端 未结 8 1590
挽巷
挽巷 2020-11-27 03:52

I have created a simple scheduled task using Spring Framework\'s @Scheduled annotation.

 @Scheduled(fixedRate = 2000)
 public void doSomething() {}
         


        
8条回答
  •  星月不相逢
    2020-11-27 04:48

    Another approach that I have not found yet. Simple, clear and thread safe.

    1. In your configuration class add annotation:

      @EnableScheduling

    2. This and next step in your class where you need start/stop scheduled task inject:

      @Autowired TaskScheduler taskScheduler;

    3. Set fields:

       private ScheduledFuture yourTaskState;
       private long fixedRate = 1000L;
      
    4. Create inner class that execute scheduled tasks eg.:

       class ScheduledTaskExecutor implements Runnable{
           @Override
           public void run() {
             // task to be executed
           }
       }
      
    5. Add start() method:

       public void start(){
           yourTaskState = taskScheduler.scheduleAtFixedRate(new ScheduledTaskExecutor(), fixedRate);
       }
      
    6. Add stop() method:

       public void stop(){
           yourTaskState.cancel(false);
       }
      

    TaskScheduler provide other common way for scheduling like: cron or delay.

    ScheduledFuture provide also isCancelled();

提交回复
热议问题