One of the lessons that we share today is the Java Timing task, which is to execute the following code at some point in the day.
public class Timermanager {
//time interval
private static final Long period_day = * * * 1000;
Public Timermanager () {
Calendar calendar = calendar.getinstance ();
/*** Custom 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 first scheduled task
//If the first time the scheduled task is performed less than the current time//at
this time, add a day to the first scheduled task so that the task executes at the next point in time. If the day is not added, the task is executed 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-delay 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 problem of time point. If you set the task at 2 o'clock in the morning. But you are releasing the program after 2 o'clock or restarting the service, in which case the task will be executed immediately, not until the next day 2 o'clock in the morning. To avoid this, you can only judge if the time to publish or restart the service is later than the time it takes to perform the task, adding one day to the base.
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) {
}
}
And then you have to configure the listener inside the web.xml.
<listener>
<listener-class>
com.listener.NFDFlightDataTaskListener
</ Listener-class>
</listener>
The above is the entire content of this article, I hope to help you learn.