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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 15:11:00  来源:igfitidea点击:

Spring : Schedule a task which takes a parameter

javaspringscheduled-tasks

提问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

According to the docsyou cant.

根据你不能的文档

Notice that the methods to be scheduled must have void returns and must not expect any arguments.

请注意,要调度的方法必须具有 void 返回值并且不能期望任何参数。

回答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 TaskSchedulerand 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));
}