How to schedule task in java code

后端 未结 2 979
别跟我提以往
别跟我提以往 2021-01-19 01:42

I know how to schedule task in spring context:

  
  

        
相关标签:
2条回答
  • 2021-01-19 02:16

    Unlike XML configuration or annotation configuration (where you can specify directly a method of a Spring managed bean), you need to create your own Runnable which will call your method.

    Say you have the following managed bean:

    @Component
    public class SchedulingBean{
        public void doSomethingPeriodically(){
        }
    }
    

    and you want to run the method inside on a dynamic cron, you have (at least) three options:

    Let SchedulingBean implement Runnable and call the doSomehtingPeriodically method from the run method

    @Component
    public class SchedulingBean implements Runnable{
        public void doSomethingPeriodically(){
    }
    @Override
    public void run(){
        doSomethingPeriodically();
        }
    }
    

    Create a new (maybe anonymous) Runnable instance that calls the method from within the managed bean. This could be a little trickier, as you will need to get the reference to that bean from the Spring context.

    Or create a new (maybe anonymous) Runnable instance that implements directly the needed functionality, without using a managed bean:

    public class SchedulingBean implements Runnable{
        public void doSomethingPeriodically(){
        }
        @Override
        public void run(){
            doSomethingPeriodically();
        }
    }
    

    (note the missing @Component)

    0 讨论(0)
  • 2021-01-19 02:21

    Just three paragraph above in your link

    public interface TaskScheduler {
    
        ScheduledFuture schedule(Runnable task, Trigger trigger);
    
        ScheduledFuture schedule(Runnable task, Date startTime);
    
        ScheduledFuture scheduleAtFixedRate(Runnable task, Date startTime, long period);
    
        ScheduledFuture scheduleAtFixedRate(Runnable task, long period);
    
        ScheduledFuture scheduleWithFixedDelay(Runnable task, Date startTime, long delay);
    
        ScheduledFuture scheduleWithFixedDelay(Runnable task, long delay);
    
    }
    

    so in scheduler.schedule(task, new CronTrigger("* 15 9-17 * * MON-FRI"));

    • scheduler is an instance of TaskScheduler
    • task is a Runnable

      Runnable exampleRunnable = new Runnable(){
      
          @Override
          public void run() {
              //To change body of implemented methods 
          }
      };
      
    0 讨论(0)
提交回复
热议问题