0

I need to create an application which loads the data into database during the night(f.i 4a.m). I found this tutorial: http://websystique.com/spring/spring-job-scheduling-with-scheduled-enablescheduling-annotations/

And this scheduling works great! However..., to somehow tell my application that it will start to use the scheduler I have to write:

 AbstractApplicationContext  context = new AnnotationConfigApplicationContext(ApplicationScheduler.class);

and... I have no idea where to put it. I cannot put it into my controller because then it will be set at that time when user enters the webpage and at the begining there will be no data. So I need this scheduler to be set up when I deploy my application on server. For example, I put my app on server at 2a.m and then it knows that at 4a.m it will download the data.

To sum up, I know how to set this scheduler to do what I want at the time I want. I just have no idea where I should set this abstract application context.

user2455862
  • 585
  • 10
  • 26
  • You don't have to write that nor do you want to write that especially not somewhere it is invoked repeatedly. Just make the bean you want to invoke/schedule part of the application context you already have. – M. Deinum Jan 26 '15 at 09:00

2 Answers2

1

You can create f.e. some class annotated with @Service and put scheduled methods within.

@Service
public class SchedulerService  {

    @Scheduled(cron="0 4 * * * ?")
    public void loadDataInDB() {
        . . .
    }
}
ancalled
  • 174
  • 6
0

Thanks for answers but I think I found the best one:

public class MyAppServletContextListener 
               implements ServletContextListener{

    @Override
    public void contextDestroyed(ServletContextEvent arg0) {
        System.out.println("ServletContextListener destroyed");
    }


            //Run this before web application is started
        @Override
        public void contextInitialized(ServletContextEvent arg0) {
            System.out.println("ServletContextListener started");   
AbstractApplicationContext  context = new AnnotationConfigApplicationContext(ApplicationScheduler.class);
        }
    }
user2455862
  • 585
  • 10
  • 26