Three ways Java performs tasks on a timed basis

Source: Internet
Author: User

1. Using java.util.Timer

This method should be the most common, but this method needs to manually start your task

Timer timer=new  timer (); Timer.schedule (new listbydaytimertask (), 10000,86400000);

The Listbydaytimertask class here must extends the run () method inside the TimerTask and then run the method inside 写你要执行的内容 .

2. Context listeners can be used in aweb container environment Servletcontextlistener

This method is convenient in a web container environment, so that the task can be run automatically after the Web server is started, without the need for manual action. Add the Listbydaylistener implements Servletcontextlistener interface to the Contextinitialized method by adding the code to start the timer in the contextdestroyed method to add the code to cancel the timer, and then in Web. XML, add Listener:

< listener>< listener-class>com.qq.customer.ListByDayListener</listener-class ></listener>

3. How to use the Spring framework:

If you use spring, then you do not need to write the timer class, add the following content in the config file Schedulingcontext-timer.xml:

<? xmlversion= "1.0"encoding= "UTF-8"?>< ! DOCTYPEbeans Public "-//spring//dtd bean//en" "Http://www.springframework.org/dtd/spring-beans.dtd"><Beans><BeanID= "Timer"class= "Org.springframework.scheduling.timer.TimerFactoryBean">< Propertyname= "Scheduledtimertasks"><List><refLocal= "MyTimeTask1"/></list></property></bean><BeanID= "Mytimetask"class= "Com.qq.timer.ListByDayTimerTask"/><BeanID= "MyTimeTask1"class= "Org.springframework.scheduling.timer.ScheduledTimerTask">< Propertyname= "TimerTask"><refBean= "Mytimetask"/></property>< Propertyname= "Delay"><value>10000</value></property>< Propertyname= "Period"><value>86400000</value></property></bean></beans> 

Three ways Java performs tasks on a timed basis

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.