When the Spring MVC Project starts, insert a timed task after the container has finished loading

Source: Internet
Author: User

In spring MVC, the container is loaded automatically when the project is started, but at ordinary times it needs to be done at the start of the project, which is used in the container, and can be accomplished by implementing the Applicationlistener interface.

A class that implements the Applicationlistener interface that is notified whenever a applicationevent is published to the ApplicationContext (that is, the context, also known as a container), Next, load a timed task at the start of the project as an example


Package com. Timer

Import Java.util.Date;

Import java.util.List;

Import Java.util.Timer;

Import Java.util.TimerTask;

Import javax.servlet.ServletContextEvent;

Import Javax.servlet.ServletContextListener;

Import org.springframework.beans.factory.annotation.Autowired;

Import Org.springframework.context.ApplicationListener;

Import org.springframework.context.event.ContextRefreshedEvent;

Import Org.springframework.stereotype.Service;

PS implementation annotation, for the container to scan the class

@Service

public class Tasktimer implements applicationlistener<contextrefreshedevent>{

@Autowired

Contents of containers used by private Xxxservice xxxservice;//

Private timer timer = null;

@Override

public void Onapplicationevent (Contextrefreshedevent evt) {

if (Evt.getapplicationcontext (). GetParent () = null) {

Createsitemap ()//calling the task to do

}

}


private void Createsitemap () {

Timer timer = new Timer ("Createsitemap", true);

Timer.schedule (New TimerTask () {

@Override

public void Run () {

Date Sysdatestar = new Date ();

System.out.println (Sysdatestar);

Date sysdateend = Dateutil.adddateminut (Sysdatestar, 10);

What you want to do when you start a project

}

}, 5000, 10*60000);

}

}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.