Spring : Schedule a task which takes a parameter

大兔子大兔子 提交于 2019-12-14 00:54:23

问题


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?


回答1:


According to the docs you cant.

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




回答2:


The Spring doc about scheduling says:

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

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)




回答3:


You can use TaskScheduler and encapsule your logic with a parameter in Runnable:

@Autowired
private TaskScheduler scheduler;

public void scheduleRules() {
    MyTask task = new MyTaskImpl(someParam);
    // new CronTrigger
    scheduler.scheduleAtFixedRate(task, Duration.ofMinutes(1));
}


来源:https://stackoverflow.com/questions/29388540/spring-schedule-a-task-which-takes-a-parameter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!