I am trying to run some job in my Spring MVC application periodically. Based on tutorials online I set up the Scheduled Job as follows:
Here is the AppInitializer (I have no setup in the XMLs):
public class AppInitializer implements WebApplicationInitializer {
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
rootContext.register(JPAConfiguration.class);
servletContext.addListener(new ContextLoaderListener(rootContext));
AnnotationConfigWebApplicationContext dispatcherServlet = new AnnotationConfigWebApplicationContext();
dispatcherServlet.register(MvcConfig.class);
ServletRegistration.Dynamic dispatcher = servletContext.addServlet("dispatcher", new DispatcherServlet(dispatcherServlet));
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("/");
}
}
Here is the configuration file:
@Configuration
@EnableScheduling
@EnableTransactionManagement
@ComponentScan(basePackages = {"com.prime.tutorials"})
@EnableJpaRepositories(basePackages = {"com.prime.tutorials.model", "com.prime.tutorials.repository"})
public class JPAConfiguration {
@Value("${jdbcURL}")
private transient String jdbcURL;
@Value("${dbPassword}")
private transient String dbPassword;
/* The usual stuff here, let me know if you want me post that as well */
}
This is the class handling the Scheduled job:
@Service
public class ScheduledJobService {
@Autowired
private PrimeRepository primeRepository
@Scheduled(fixedDelayString = "${fixedDelay.in.milliseconds:10000}")
public void run() {
System.out.println("Current time is :: " + Calendar.getInstance().getTime());
}
}
As you can see the fixed delay is set to 10 secs but my job is running every 5 seconds. I am not able to understand why this is happening. I went through the questions posted in regards to this topic before but I havent been able to find a matching solution.
Other posts suggest that in such cases the beans might be getting initialized twice but based on my config I am not sure how that is happening.
Similar Question This question above seems like an exact duplicate of the what I am asking but the OP hasnt posted his/her configuration or setup. Most of the answers suggest double initialization of the components which I am not sure is the case with my application.
Current time is :: Sun Jun 10 22:53:16 EDT 2018
Current time is :: Sun Jun 10 22:53:22 EDT 2018
Current time is :: Sun Jun 10 22:53:26 EDT 2018
Current time is :: Sun Jun 10 22:53:32 EDT 2018
Current time is :: Sun Jun 10 22:53:36 EDT 2018
EDIT-1
Based on suggestion from Jennifer I do see that two instances are calling the run method.
EDIT-2
M.Deinum's guess was absolutely right, my MvcConfig.java was annotated by @ComponentScan which made the Schedule Job run twice. But after removing that annotation from the MvcConfig.java my end-points stopped working. What am I missing here..