Examples of Java timing tasks

  • 2020-04-01 04:07:05
  • OfStack

One lesson I want to share with you today is the timing task in Java, which is to execute the following code at a certain point in the day.


public class TimerManager {
 
 //The time interval
 private static final long PERIOD_DAY = 24 * 60 * 60 * 1000;
 
 public TimerManager() {
 Calendar calendar = Calendar.getInstance();
    
 
 
 calendar.set(Calendar.HOUR_OF_DAY, 2);
 calendar.set(Calendar.MINUTE, 0);
 calendar.set(Calendar.SECOND, 0);
  
 Date date=calendar.getTime(); //The time of the first scheduled task
  
 // if The time of the first scheduled task  Less than   Current time 
 // At this point in  The time of the first scheduled task  Add one more day for this task to execute at the next point in time. If not added a day, the task will be carried out immediately. 
 if (date.before(new Date())) {
   date = this.addDay(date, 1);
 }
  
 Timer timer = new Timer();
  
 NFDFlightDataTimerTask task = new NFDFlightDataTimerTask();
 //Schedule the specified task to begin repeated, fixed delay execution at the specified time.
 timer.schedule(task,date,PERIOD_DAY);
 }
 
 //Add or subtract 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 the class TimerManager, you must pay attention to the point in time. If you set the task for 2 a.m. But if you've released a program or restarted a service after 2 a.m., the task will be executed immediately, rather than waiting until 2 a.m. To avoid this, you can only add one more day if the service is released or restarted later than the scheduled execution time.


public class NFDFlightDataTimerTask extends TimerTask {
 
 private static Logger log = Logger.getLogger(NFDFlightDataTimerTask.class);
 
 @Override
 public void run() {
 try {
  //Write what you want to execute here
  
 } catch (Exception e) {
  log.info("------------- An exception occurred to the parsing information --------------");
 }
 }
}
 
public class NFDFlightDataTaskListener implements ServletContextListener {
 
 public void contextInitialized(ServletContextEvent event) {
 new TimerManager();
 }
 
 public void contextDestroyed(ServletContextEvent event) {
 }
 
}

Then configure the listener in 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 with your study.


Related articles: