春季启动:如何参数化@Scheduled [英] Spring boot: How to parameterize @Scheduled

查看:57
本文介绍了春季启动:如何参数化@Scheduled的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Spring的新手,只是从头开始了解它的用途.

I am new to Spring and have only scratched the surface of what can be done with it.

我遇到一种情况,需要使用 @Scheduled 批注设置重复任务.该速率被指定为对象的成员字段,该对象传递给封装表示任务的方法的类.

I have a situation where I need to set up a recurring task using the @Scheduled annotation. The rate is specified as a member field in an object that is passed to the class encapsulating the method representing the task.

我使用了允许访问配置或环境的机制,例如 @Scheduled(fixedRateString ="$ {some.property:default}");这很棒.

I've used the mechanism that allows for accessing the configuration or environment, e.g. @Scheduled(fixedRateString = "${some.property:default}"); this works great.

我不知道该怎么做,是将对象中的值插入 @Scheduled .

What I don't know how to do is insert the value from an object into the @Scheduled.

例如:

class MyClass {
  private MyObject myObj;

  public MyClass(MyObject myObj) {
    this.myObj = myObj;
  }

  @Scheduled(fixedRateString = "${myObj.rate:5000}")
  private void someTask() {
    ...
  }
}

上面的代码当然不起作用,我只是举一个我想做的事的例子.

The code above, of course, does not work, I'm just giving an example of what I'm trying to do.

任何建议将不胜感激.

推荐答案

不幸的是,spring bean创建过程不会读取这样的局部变量.

Unfortunately the spring bean creation process will not read local variables like that.

您可以使用Spring TaskScheduler类.

You can use the Spring TaskScheduler class.

基本上,您只需要定义一个线程池,即可用于运行调度的任务(作为bean)并运行taskScheduler.schedule(可运行,新的CronTrigger("* * * * *"))).这里有一个详细的示例:

Essentially you just have to define a thread pool that you will use to run the scheduled tasks (as a bean) and run taskScheduler.schedule(runnable, new CronTrigger("* * * * *")). There is a detailed example here:

https://www.baeldung.com/spring-task-scheduler

这篇关于春季启动:如何参数化@Scheduled的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆