A simple method to implement timed tasks under Web application
In Web mode, if we want to implement certain tasks on a regular basis, in addition to using quartz and other third-party open source tools, we can use timer and Timetask to complete the specified timing tasks:
The first step: Create a task management class, implement Servletcontextlistener interface
The following is a reference fragment: public class TaskManager implements Servletcontextlistener {
/**
* Number of milliseconds per day
*/
public static final Long period_day = Dateutils.millis_in_day;
/**
* Number of milliseconds in a week
*/
public static final Long Period_week = Period_day * 7;
/**
* No delay
*/
public static final Long no_delay = 0;
/**
* Timer
*/
private timer timer;
/**
* Initialize tasks when Web application starts
*/
public void contextinitialized (Servletcontextevent event) {
Defining timers
Timer = new Timer ("Database table Backup", true);
Start a backup task, run once a month (4 weeks)
Timer.schedule (New Backuptabletask (), No_delay, Period_week * 4);
Timer.schedule (New Backuptabletask (), No_delay, 30000);
}
/**
* Stop the task at the end of the Web application
*/
public void contextdestroyed (Servletcontextevent event) {
Timer.cancel (); Timer destruction
}
}
Step Two: Create a Time task class
The following is a reference fragment: public class Backuptabletask extends TimerTask {
private static log log = Logfactory.getlog (Backuptabletask.class);
private static Boolean isrunning = false;
public void Run () {
if (!isrunning) {
IsRunning = true;
Log.debug ("Start the task ..."); Start Task
Working add what you want Todo
Log.debug ("Perform the task Complete ..."); Mission accomplished
IsRunning = false;
} else {
Log.debug ("Last task execution is not finished ..."); Last task execution not finished
}
}
}
Step three: Add a listener to the web
The following is a quote fragment: <listener>
<listener-class>***. Taskmanager</listener-class>
<description> tasks to be performed on a regular basis </description>
</listener>
When the Web server is started, the task is also started and periodically executed.