Reputation: 2566
I just want to run my spring boot main method periodically by using @scheduler annotation. I have specified some additional code which will perform some pre-action before it enables REST services.
@EnableScheduling
@SpringBootApplication
public class SpringBootJDBCApp {
@Autowired
ITest testService;
public static void main(String args[]) throws Exception {
PersistenceValidation.cloneGit();
PersistenceValidation.dataPersistance();
PersistenceValidation.cleanUp();
ApplicationContext context = SpringApplication
.run(SpringBootJDBCApp.class);
ITest testService = context.getBean(ITestService.class);
testService.getAllData();
}
}
I want to run the above main method every 10seconds once. and Added @Schedule annotation at main method. But It throws an exception:
Expected behavior as per doc @Scheduler should be called a method which doesn't have args[]
I wanna use @Scheduler
annotation in main method as below:
@Scheduled(initialDelay = 1000, fixedRate = 10000)
public static void main(String args[]) throws Exception {
PersistenceValidation.cloneGit();
PersistenceValidation.dataPersistance();
PersistenceValidation.cleanUp();
ApplicationContext context = SpringApplication.run(SpringBootJDBCApp.class);
ITest testService = context.getBean(ITestService.class);
testService.getAllData();
}
Error:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'springBootJDBCApp': Initialization of bean failed; nested exception is java.lang.IllegalStateException: Encountered invalid @Scheduled method 'main': Only no-arg methods may be annotated with @Scheduled
Is there any other way to achieve this task? I wanna run the entire things which are mentioned in the main method periodically.
Any leads?
Upvotes: 2
Views: 7651
Reputation: 44368
The scheduled method annotated with @Scheduled
annotation must have no arguments because the annotation doesn't provide any input. The Spring-docs of @Scheduled
sais:
The annotated method must expect no arguments. It will typically have a void return type; if not, the returned value will be ignored when called through the scheduler.
You annotated the method public static void main(String args[])
which has an array as an argument. You have to just wrap the content in the main(String args[])
into a different method. Note you don't use args[]
at all.
Upvotes: 3