Java Bean ::如何创建动态执行的方法(可以重新调整)

时间:2014-04-28 14:12:37

标签: java spring timer

我希望创建一个能够每N分钟执行一些代码的bean。必须能够调整此bean(不仅仅是使用@Scheduled(fixed = xxx))

概要

工人阶级

class Worker{

  @Autowired
  MyService myservice;

  myService.notifyUser(10);
}

服务类

class MyService{

  public void notifyUser(int nMinutes){
       //Busy Code
  }
}

1 个答案:

答案 0 :(得分:0)

您可以使用java.util.Timerjava.util.TimerTask

final Timer timer = new Timer();
    //To run the task once you would do:
    timer.schedule(new TimerTask() {
          @Override
          public void run() {
              System.out.println("running Task..");
          }
        }, 5);

      // task repeat after the duration time you need to do like this
    timer.scheduleAtFixedRate(new TimerTask() {

        @Override
        public void run() {
            System.out.println("Repeating running Task..");
        }
    }, 1*60*1000, 1*60*1000); // repeat after one minute

还有TimerService,请参阅doc here