Issue
I have one class Task with a @Scheduled method as below
public class Task{
public void task(){}
}
TaskConfig creates 2 different beans of same class :
public class TaskConfig{
@Bean("task1")
public Task getTask1(){return new Task();}
@Bean("task2")
public Task getTask1(){return new Task();}
}
Using xml based configuration I can create 2 scheduler for same method as below, which will run at differenct time. :
<task:scheduled-tasks >
<task:scheduled ref="task1" method="task" cron="*/5 * * * * ?" />
<task:scheduled ref="task2" method="task" cron="*/30 * * * * ?" />
</task:scheduled-tasks>
But how to achieve this same scenario in Spring 5 Annotation based ? Please suggest.Thanks in advance !
Solution
You could use @Scheduled
annotation and annotate your method you want to execute: https://docs.spring.io/spring/docs/3.2.x/spring-framework-reference/html/scheduling.html#scheduling-annotation-support You can also define cron like expressions.
You should also make sure the scheduling is enabled: https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/scheduling/annotation/EnableScheduling.html
EDIT:
public class TaskConfig{
@Bean("task1")
public Task getTask1(){return new Task() {
@Override
@Scheduled
public void task(){super.task();}
};
}
@Bean("task2")
public Task getTask2(){return new Task() {
@Override
@Scheduled
public void task(){super.task();}
};
}
Answered By - schoener
Answer Checked By - Candace Johnson (JavaFixing Volunteer)