Java timed tasks that perform tasks on a daily schedule. The following is the entire code for this example.
public class Timermanager {
Time interval
Private static final Long Period_day = 24 * 60 * 60 * 1000;
Public Timermanager () {
Calendar calendar = Calendar.getinstance ();
/*** customizing Daily 2:00 execution Method ***/
Calendar.set (Calendar.hour_of_day, 2);
Calendar.set (calendar.minute, 0);
Calendar.set (Calendar.second, 0);
Date Date=calendar.gettime (); Time of the first execution of a scheduled task
If the time to perform the first scheduled task is less than the current time
At this point, the time for the first scheduled task is added to the day so that the task executes at the next point in time. If one day is not added, the task executes immediately.
if (Date.before (new Date ())) {
Date = This.addday (date, 1);
}
Timer timer = new timer ();
Nfdflightdatatimertask task = new Nfdflightdatatimertask ();
Schedules the specified task to begin repeating fixed deferred execution at a specified time.
Timer.schedule (Task,date,period_day);
}
Increase or decrease the number of days
Public date Addday (date date, int num) {
Calendar Startdt = Calendar.getinstance ();
Startdt.settime (date);
Startdt.add (Calendar.day_of_month, num);
return Startdt.gettime ();
}
}
In Timermanager this class, we must pay attention to the time point of the problem. If you set the task to run at 2 o'clock in the morning. But you were after 2 o'clock.
The program is released or restarted, in which case the task executes immediately, rather than waiting until 2 o'clock in the morning the next day. In order to avoid this situation
Occurs, only to judge, if the time to publish or restart the service is later than the time of the scheduled execution of the task, on this basis plus one day.
public class Nfdflightdatatimertask extends TimerTask {
private static Logger log = Logger.getlogger (Nfdflightdatatimertask.class);
@Override
public void Run () {
try {
Write what you want to do here.
} catch (Exception e) {
Log.info ("-------------Parsing information Exception--------------");
}
}
}
public class Nfdflightdatatasklistener implements Servletcontextlistener {
public void contextinitialized (Servletcontextevent event) {
New Timermanager ();
}
public void contextdestroyed (Servletcontextevent event) {
}
}
Then you configure the listener in Web. xml
<listener>
<listener-class>
Com.listener.NFDFlightDataTaskListener
</listener-class>
</listener>
Java Timer Task Scheduler