简体   繁体   English

在应用程序开始使用Spring之后执行一个方法

[英]Execute a method after the application starts using Spring

I have this structure in my Service component in my Spring: 我的Spring服务组件中具有以下结构:

@Autowired
PointController controller;
@Autowired
ParametroService parametroService;

Timer timer = new Timer();
TimerTask timerTask = new TimerTask() {
    @Override
    public void run() {
        List<IntRaptMec> allPointments =  getNotValidated();

        for(IntRaptMec pointment : allPointments) {
           controller.validate(pointment.getIdTemp());
        }
    }
};        

public void doValidationsTask() {       

    Parametro parametroTempo = parametroService.getParametro("1", "ATRC_MEC", "TEMPO_VERIFICACAO");
    timer.scheduleAtFixedRate(
            timerTask,
            Integer.parseInt(parametroTempo.getValor()) * oneMinute,
            Integer.parseInt(parametroTempo.getValor()) * oneMinute
    );  

}

All that I want is that after the Spring Application fully initializes it will execute the method run() inside the TimerTask. 我想要的就是在Spring Application完全初始化之后,它将在TimerTask内部执行run()方法。 Then, after a given time in minutes that will be get from the parametroService.getParametro(), execute this task again. 然后,在几分钟内从parametroService.getParametro()获得给定时间后,再次执行此任务。

I tried to follow this link from the docs: https://docs.spring.io/spring/docs/current/spring-framework-reference/integration.html#scheduling-annotation-support 我试图按照以下文档中的链接操作: https//docs.spring.io/spring/docs/current/spring-framework-reference/integration.html#scheduling-annotation-support

But seems that I can't dinamically sets the Delay time that a specific task will be executed 但似乎我无法从动力学上设置将执行特定任务的延迟时间

You can annotate your run() method with @EventListener or create a new such annotated method which will call run() : 您可以使用@EventListener注释run()方法,或创建一个新的此类注释方法,该方法将调用run()

@EventListener
public void handleContextRefresh(ContextRefreshedEvent event) {
    run();
}

If you don't use context which supports refresh() operation, you should be fine. 如果不使用支持refresh()操作的上下文,那应该没问题。 If you use such context (and you don't want run() to execute on context refresh) make sure you store this state within your bean. 如果使用这样的上下文(并且您不希望run()在上下文刷新时执行),请确保将此状态存储在bean中。

More info on standard Spring events . 有关标准Spring事件的更多信息

You are correct that annotation @Scheduled does not allow you to read delay parameter dynamically. 正确的是,注释@Scheduled不允许您动态读取delay参数。 For that reason and because this annotation takes delay parameter only in milliseconds or as crone expression which is not user friendly, I wrote my own utility that does it. 因此,由于该批注仅以毫秒为单位或不方便用户使用的crone表达式采用了delay参数,因此我编写了自己的实用程序来执行此操作。 The Utility is available as part of Open Source MgntUtils library. 该实用程序可作为开源MgntUtils库的一部分使用。 You will need to write your classes that will extend classes provided in the library and then you will get the desired functionality. 您将需要编写类来扩展库中提供的类,然后才能获得所需的功能。 But it does require a little bit of work. 但这确实需要一点工作。 However the library comes with example package that has source code of working example with detailed explanation in javadoc. 但是,该库随附示例包,该包具有在Javadoc中带有详细说明的工作示例的源代码。 If you are interested library is available at Github and at Maven Central . 如果您有兴趣,可以在GithubMaven Central上找到图书馆。 In both places it is available with sources and javadoc. 在这两个地方都可以使用source和javadoc。 The desired feature is described in detail in javadoc. 所需的功能在javadoc中进行了详细描述。 If you download and unzip javadoc into folder c:\\tmp then look at URL file:///C:/tmp/javadoc/com/mgnt/lifecycle/management/backgroundrunner/package-summary.html for detailed description on how to use this feature. 如果将javadoc下载并解压缩到文件夹c:\\ tmp中,请查看URL 文件:/// C:/tmp/javadoc/com/mgnt/lifecycle/management/backgroundrunner/package-summary.html ,以获取有关使用方法的详细说明此功能。 For working code example look in the sources at package com.mgnt.lifecycle.management.backgroundrunner.example 有关工作代码示例,请查看包com.mgnt.lifecycle.management.backgroundrunner.example中的源代码。
Also, there is an article that explains about the features of the library, except that this particular feature is not described in that article yet. 另外,有一篇文章介绍了该库的功能,但该文章中尚未描述该特定功能。 Here is the link: Open Source Java library with stack trace filtering, Silent String parsing, Unicode converter and Version comparison 这里是链接: 具有堆栈跟踪过滤,静默字符串解析,Unicode转换器和版本比较的开源Java库

You can implement a spring SmartLifecycle interface. 您可以实现spring SmartLifecycle接口。 This will get invoked when Spring context is loaded completely. 完全加载Spring上下文时,将调用此方法。 And Then you can start the timertask. 然后,您可以启动timertask。

public class TimerTaskInvoker implements SmartLifecycle{
@override
public void start(){
  timer.scheduleAtFixedRate(timerTask);
  }
}

You can check the reference - https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/context/SmartLifecycle.html 您可以检查参考-https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/context/SmartLifecycle.html

@PostConstruct may be the annotation you need. @PostConstruct可能是您需要的注释。

https://www.baeldung.com/running-setup-logic-on-startup-in-spring https://www.baeldung.com/running-setup-logic-on-startup-in-spring

You can use spring scheduler and specify the initialDelay and fixedRate using the @Scheduled annotation. 您可以使用spring调度程序 ,并使用@Scheduled批注指定initialDelayfixedRate

@EnableScheduling
class CustomScheduler{

  @Scheduled(fixedRate = 1000, initialDelay = 1000)
  public void taskYouWantToPerform() {

      List<IntRaptMec> allPointments =  getNotValidated();
      for(IntRaptMec pointment : allPointments) {
          controller.validate(pointment.getIdTemp());
      }
  }
}

For more details refer this 有关更多详细信息,请参阅

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM