Java Web implements an example of adding a timed task

  • 2020-12-22 17:37:38
  • OfStack

This article illustrates how Java Web implements the addition of timed tasks. To share for your reference, the details are as follows:

Timing task time control class


/**
 *  Timed task time control 
 *
 * @author liming
 *
 */
public class TimerManager {
  //  The time interval 
  private static final long PERIOD_DAY = 24 * 60 * 60 * 1000;
  public TimerManager() {
    Calendar calendar = Calendar.getInstance();
    /***  Custom daily 00:00 Execution method  ***/
    calendar.set(Calendar.HOUR_OF_DAY, 0);
    calendar.set(Calendar.MINUTE, 0);
    calendar.set(Calendar.SECOND, 0);
    Date date = calendar.getTime(); // The time it takes to perform a scheduled task 
    //  When starting the server 1 A timed task executes immediately when the time it is executing is less than the current time. 
    //  Therefore, in order to prevent the repeated execution of the task caused by the server restart, the time of executing the timed task needs to be changed to 2 Days. 
    if (date.before(new Date())) {
      date = this.addDay(date, 1);
    }
    Timer timer = new Timer();
    DailyDataTimerTask task = new DailyDataTimerTask();
    //  Task execution interval. 
    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();
  }
}

Timing task operation principal class


/**
 *  Timing task operation body 
 *
 * @author liming
 *
 */
public class DailyDataTimerTask extends TimerTask {
  private static Logger log = Logger.getLogger(DailyDataTimerTask.class);
  @Override
  public void run() {
    try {
      // Write what you want to execute here 
      System.out.println("come in DailyDataTimerTask");
    } catch (Exception e) {
      log.info("------------- An exception has occurred for parsing information --------------");
    }
  }
}

Timing task listener


/**
 *  Timing task listener 
 *
 * @author liming
 *
 */
public class DailyDataTaskListener implements ServletContextListener {
  public void contextInitialized(ServletContextEvent event) {
    new TimerManager();
  }
  public void contextDestroyed(ServletContextEvent event) {
  }
}

web.xml adds listeners


<!-- Load the daily data update timing task file -->
<listener>
    <listener-class>
      com.honsto.web.job.DailyDataTaskListener
    </listener-class>
</listener>

For more information about java, please refer to Java Data Structure and Algorithm Tutorial, Java File and Directory Operation Skills Summary, Java Operation Skills Summary of DOM Node and Java Cache Operation Skills Summary.

I hope this article has been helpful in java programming.


Related articles: