?????????е?????

???????????????????TimerTask???????Runnable??

??????????run()?????????????????????????????и÷?????????????????

?????????????????????

??????Щ??????????com.test.time.ScheduleTask?????????????ServletContextListener?е????????????????????????????????????????????????????????

??????????????????????

???????????

???????????????????????????????????????????磺12:08:56??

????????web.xml????????????????????????????

???????????????

package com.test.time;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.TimerTask;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

/**
 * ??????????????web.xml?м???????
 * @author MyLove
 *
 */
public class ScheduleTask extends TimerTask implements ServletContextListener
{
 /**
  * ??????TimerTask????????????????????и?run()??????
  */
 @Override
 public void run()
 {
  // TODO Auto-generated method stub
  System.out.println(ScheduleTask.getSystemTime());
 }

 /**
  * ????????????????????????С?
  */
 @Override
 public void contextDestroyed(ServletContextEvent arg0)
 {
  // TODO Auto-generated method stub
 
 }

 /**
  * ????????????????ServletContextListener?????????????????????С?
  */
 @Override
 public void contextInitialized(ServletContextEvent arg0)
 {
  //?????????????????????????????????????????????С?
  ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
 
  //?????????е?????????и?????е?run????????????????Runnable??
  ScheduleTask task = new ScheduleTask();
 
  //????????????????饗???????????????????
  long firstTime = 1;
 
  //???????к???е???????
  long period = 1;
 
  //????????????TimeUnit.SECONDS???λ???
  scheduler.scheduleAtFixedRate(task?? firstTime?? period??TimeUnit.SECONDS);
 }
 
 /**
  * ????????
  * <p>??????е?????
  * <p>G  Era
  * <p>y  ??  Year
  * <p>M  ???е??·?
  * <p>w  ???е?????
  * <p>W  ?·??е?????
  * <p>D  ???е?????
  * <p>d  ?·??е?????
  * <p>F  ?·??е?????
  * <p>E  ?????е?????
  * <p>a  Am/pm ???
  * <p>H  ?е?С?????0-23??
  * <p>k  ?е?С?????1-24??
  * <p>K  am/pm ?е?С?????0-11??
  * <p>h  am/pm ?е?С?????1-12??
  * <p>m  С??е??????
  * <p>s  ?????е?????
  * <p>S  ??????
  * <p>z  ???
  * <p>Z  ???
  *
  * ?????"yyyy.MM.dd G 'at' HH:mm:ss z"??
  * ???2001.07.04 AD at 12:08:56 PDT ??
  * ???????е???????Сд??С?
  * @return ?????????????????????????磺19:56:43??
  */
 public static String getSystemTime()
 {
  //?????????????????
  Calendar calendar = Calendar.getInstance();
 
  //???????????
  SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm:ss");
 
  //???????????л??Date???????????????????????
  String time = simpleDateFormat.format(calendar.getTime());
 
  return time;
 }
}