Timed Task--timer () implementation

Source: Internet
Author: User

The Java timer and the TimerTask class can help us implement the timer function, using the servlet listener to perform some work after the Web service starts. The combination of the two can be implemented in the Web application timer function. 1. Plan Class Code Scheduler

public void Sendscheduler (String datestr) {
		Final timer timer = new timer ();
		SimpleDateFormat formatter = new SimpleDateFormat ("Yyyy-mm-dd HH:mm:ss");
		Parseposition pos = new parseposition (0);
		Date currenttime = Formatter.parse (Datestr, POS);
		Timer.schedule (New TimerTask () {
			@Override public
			void Run () {
				//can be placed in the method to be executed) after the scheduled start of operation 1 seconds per interval
				System.out.println ("The plan begins.") "+ i++);
				Timer.cancel (); Schedule Cancellation
			}
		, currenttime, 1000);
	
2. Writing listening

public class Schedulerlistener implements servletcontextlistener{public

	void contextdestroyed ( Servletcontextevent arg0) {
	} public

	void contextinitialized (Servletcontextevent arg0) {
		SYSTEM.OUT.PRINTLN ("Service Opening time:" +new date ());
		Scheduler Scheduler = new Scheduler ();
		Scheduler.sendscheduler ("2012-12-26 17:00:00");
	}
	
3. Listening Configuration

<listener>
  <listener-class>org.chh.scheduler.listener.SchedulerListener</listener-class>
</listener>




Related Article

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.