java-How to implement Timer function

Source: Internet
Author: User
Tags date implement log
java-How to implement Timer function

2004-11-8
Author:meanson Wang
Email:meansonw@hotmail.com
Date:2004-11-8
java-How to implement Timer function

1.listener class
Package timer;

Import Java.util.TimerTask;
Import Java.util.Timer;
Import javax.servlet.*;

public class Remindlistener implements Servletcontextlistener {
Private Java.util.Timer Timer = null;
public void contextinitialized (Servletcontextevent sce) {
Timer = new Java.util.Timer (true);
Sce.getservletcontext (). log (new java.util.Date () + "Timer start up!");
Timer.schedule (New Remindtask (), 0,1*60*1000);//1 minute roll
Sce.getservletcontext (). log (new java.util.Date () + "Schedule loaded!");
}
public void contextdestroyed (Servletcontextevent sce) {
Timer.cancel ();
Sce.getservletcontext (). log (new java.util.Date () + "Timer destroyed!");
}

}

2.Task class
Package timer;

Import Java.util.TimerTask;
Import Java.util.Calendar;

public class Remindtask extends timertask{
private static final int c_schedule_hour = 15;
private static Boolean isrunning = false;
Public Remindtask () {

}
public void Run () {
Calendar cal = Calendar.getinstance ();
if (!isrunning) {
if (C_schedule_hour = = Cal.get (calendar.hour_of_day)) {
IsRunning = true;
System.out.println (New Java.util.Date () + "task start");
TODO for example
int i = 0;
while (i++ < 10) {
System.out.println (New Java.util.Date () + "Done!task" + i + "/" + 10);
}
IsRunning = false;
System.out.println (New Java.util.Date () + "all Task done!");
}
}
Else
{
System.out.println (New Java.util.Date () + "Task existed!");
}
}
}

3.loadonstart in Web.xml
<listener>
<listener-class>timer. Remindlistener</listener-class>
</listener>

4.restart Server



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.