java Spring:安排一个带有参数的任务
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29388540/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Spring : Schedule a task which takes a parameter
提问by Shashank Vashistha
I have a class with the following function:
我有一个具有以下功能的类:
public class classA{
...
...
void function_to_be_scheduled(String param){
...
...
}
}
I want to schedule the function using the scheduled-tasks element of the task namespace.
我想使用任务命名空间的调度任务元素来调度函数。
<task:scheduled-tasks>
<task:scheduled ref="beanA" method="function_to_be_scheduled" cron="${cron}"/>
</task:scheduled-tasks>
How do i pass the parameter to the function which i want to schedule?
如何将参数传递给我要调度的函数?
回答by Robert Niestroj
回答by Giovanni
The Spring doc about schedulingsays:
关于调度的 Spring 文档说:
Notice that the methods to be scheduled must have void returns and must not expect any arguments
请注意,要调度的方法必须返回 void 并且不能期望任何参数
Since the parameter comes from the Spring config file you can declare a bean (es beanB which wraps beanA) in the spring file, inject the parameter you need in the bean and the schedule the execution of a method of the bean which knows the parameter (it could be a simple wrapper of your beanA)
由于参数来自 Spring 配置文件,因此您可以在 spring 文件中声明一个 bean(es beanB 包装 beanA),在 bean 中注入您需要的参数,并安排执行知道参数的 bean 的方法(它可能是您的 beanA 的简单包装器)
回答by Leos Literak
You can use TaskScheduler
and encapsule your logic with a parameter in Runnable
:
您可以使用TaskScheduler
以下参数使用和封装您的逻辑Runnable
:
@Autowired
private TaskScheduler scheduler;
public void scheduleRules() {
MyTask task = new MyTaskImpl(someParam);
// new CronTrigger
scheduler.scheduleAtFixedRate(task, Duration.ofMinutes(1));
}