Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring : Schedule a task which takes a parameter

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?

like image 416
Shashank Vashistha Avatar asked Apr 01 '15 10:04

Shashank Vashistha


People also ask

How do you dynamically schedule a spring batch job?

When you want to schedule a job in Spring Batch, you annotate it with @Scheduled(cron = "your-cron-expression") . This is "static" since you can't put a variable for the cron expression : it is assigned before runtime. Here, you can put a variable in CronTrigger.

What is @scheduled in Java?

The schedule (TimerTask task, Date time) method of Timer class is used to schedule the task for execution at the given time. If the time given is in the past, the task is scheduled at that movement for execution.

How do you schedule a task in Java?

One of the methods in the Timer class is the void schedule(Timertask task, Date time) method. This method schedules the specified task for execution at the specified time. If the time is in the past, it schedules the task for immediate execution.


2 Answers

According to the docs you cant.

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

like image 158
Robert Niestroj Avatar answered Sep 28 '22 11:09

Robert Niestroj


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)

like image 33
Giovanni Avatar answered Sep 28 '22 11:09

Giovanni