Java scheduled tasks: scheduled tasks are executed on a daily basis. All of the examples are as follows:Code.
Public class timermanager {
// Time Interval
PrivateStatIC final long period_day = 24*60*60*1000;
Public timermanager (){
Calendar calendar = calendar. getinstaNCE ();
/*** Customize the daily execution method ***/
Calendar. Set (Calendar. hour_of_day, 2 );
Calendar. Set (calendar. Minute, 0 );
Calendar. Set (calendar. Second, 0 );
Date Date = Calendar. gettime (); // The time when the scheduled task is executed for the first time
// If the time for the first scheduled task execution is less than the current time
// Add one day to the first scheduled task so that the task can be executed at the next time point. If one day is not added, the task will be executed immediately.
If (date. Before (new date ())){
Date = this. Dd Day (date, 1 );
}
Timer Time R = new timer ();
Nfdflightdatatimertask task = new nfdflightdatatimertask ();
// Schedule the specified task to execute at a fixed delay at a specified time.
Timer. sche Du Le (task, date, period_day );
}
// increase or decrease the number of days
Public date addday (date, int num) {
calendar startdt = calendar. getinstance ();
startdt. settime (date);
startdt. add (calendar. day_of_month, num);
return startdt. gettime ();
}< BR style = "word-wrap: break-word; Word-break: Break-all ">
}
In the timermanager class, you must pay attention to time points. If you want to execute the task at a.m. But after
ReleasedProgramOr restart the service. In this case, the task will be executed immediately, instead of waiting until the next day. To avoid this situation
If the service is released or restarted later than the scheduled task execution time, add one day.
Public class nfdflightdatatimertask
ExTends timertask {
Private Static logger log = logger. getlogger (nfdflightdatatimertask. Class );
@ overr id E
Public void run () {
tr Y {
// enter the content you want to execute
}< u> CAT CH (exception e) {
log.info (" ------------- parsing information exception ------------ ");
}< BR style =" word-wrap: Break-word; Word-break: break-all ">
}< BR style =" word-wrap: Break-word; Word-break: Break-all ">< BR >}
Public class nfdflightdatatasklistener implements servletcontextlistener {
Public void contextinitialized (servletcontextevent event ){
New timermanager ();
}
Public void contextdestroyed (servletcontextevent event ){
}
}
Configure the listener in Web. xml.
<Listener>
<Listener-class>
Com. listener. nfdflightdatatasklistener
</Listener-class>
</Listener>