Recently, a scheduled collection program needs to be compiled for the project, and a very simple method to deploy the scheduled process-using the listener and timer.
First, write a servlet to start the timer and schedule the task. The reference code is as follows:
Import javax. servlet. servletcontextevent;
Public class mytimer extends javax. servlet. http. httpservlet implements
Javax. servlet. servletcontextlistener {
// Private Static final long serialversionuid = 1l;
Private java. util. Timer timer = NULL;
Public void contextinitialized (servletcontextevent event ){
Timer = new java. util. Timer (true );
System. Out. println ("timer started ");
Timer. Schedule (New mytimertask (), 0, 24*60*60*1000 );
System. Out. println ("added task scheduling table ");
}
Public void contextdestroyed (servletcontextevent event ){
Timer. Cancel ();
System. Out. println ("timer destruction ");
}
}
Java. util. timer. the schedule (timertask task, long delay, long period) method has the following parameters: Task class, latency (unit: milliseconds), and cycle (unit: milliseconds ). According to my settings, it runs every 24 hours.
Then the task scheduling class:
Import java. util. calendar;
Import java. util. timertask;
Public class mytimertask extends timertask {
Private Static final int c_schedule_hour = 22;
Private Static Boolean isrunning = false;
@ Override
Public void run (){
Calendar Cal = calendar. getinstance ();
If (! Isrunning ){
If (c_schedule_hour <Cal. Get (calendar. hour_of_day )){
Isrunning = true;
System. Out. println ("starting to execute a specified task ");
/* Any code can be used here */
Isrunning = false;
System. Out. println ("End of task execution ")
}
} Else {
System. Out. println ("the last task has not been completed ");
}
}
}
Here, c_schedule_hour is the task execution time period. According to my requirements, my collection program is executed after every day.
Finally, configure the listener:
Add the following code in Web. xml. Of course, the servlet name must be replaced with the actual one.
<Listener>
<Listener-class> com. Test. mytimer </listener-class>
</Listener>
Important:
1. The Listener is initialized when the server is enabled.
Configuration:
<Listener>
<Listener-class> com. pp. mytimer </listener-class>
</Listener>
Public class mytimer extends httpservlet implements servletcontextlistener
{// The timer inherits the listener class and sets it to execute a task once every 10 seconds.
Timer. Schedule (New mytimertask (), 0, 10*1000 );
..
}
2.
In this way, mytimetask is automatically executed 10 seconds after the server is started.
Public class mytimertask extends timertask {
Public void run (){...}