Stack Overflow Asked by Bishonen_PL on November 4, 2021
The below method refreshDatasets is executed twice when I run the app. Any idea what I messed up with the configuration of Spring (annotation based)?
SchedulingTasks
@Component
@EnableScheduling
public class SchedulingTasks {
private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
@Autowired
public TestClass testclass;
@Scheduled(fixedDelay = 1 * 60 * 60 * 1000)
public void refreshDatasets() {
testclass.simpleTest();
System.out.println("The time is now " + dateFormat.format(new Date()));
}
}
TestClass
@Component
public class TestClass {
public void simpleTest() {
System.out.println("FINISHED");
}
}
Configuration
@Configuration
@ComponentScan(basePackages = "com.some.analytics.scripts",
excludeFilters = {@ComponentScan.Filter (
type= FilterType.ANNOTATION,
value=Configuration.class)})
public class ScriptsConfig {
@Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
PropertySourcesPlaceholderConfigurer p = new PropertySourcesPlaceholderConfigurer();
p.setIgnoreResourceNotFound(true);
return p;
}
}
Main
public class Scripts {
public static void main(String[] args) {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(ScriptsConfig.class);
SchedulingTasks schedulingTasks = ctx.getBean(SchedulingTasks.class);
schedulingTasks.refreshDatasets();
}
}
When running the main method, I get the following output:
FINISHED The time is now 11:08:39
FINISHED The time is now 11:08:39
When using the @EnableScheduling
annotation, Spring creates a TaskExecutor
in the background. This will schedule all the @Scheduled
methods. In the case of methods with fixedDelay
, they will be fired instantly (unless initialDelay
is set).
You are also programatically executing the task, so you have two executions:
You should remove the manual invocation, and everything should work as expected.
You can find more information in https://spring.io/guides/gs/scheduling-tasks/ and https://docs.spring.io/spring/docs/current/spring-framework-reference/integration.html#scheduling-task-scheduler
Answered by Pablo.Barrientos on November 4, 2021
Get help from others!
Recent Questions
Recent Answers
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP