public class TimerTest{
public static void main(String[] args){
int delay=5000;//延迟5秒
Timer timer=new Timer();//生成一个Timer对象
NewTask myTask=new NewTask();//初始化我们的任务
timer.schedule(yourTask,delay);//还有其他重载方法...
}
}
class NewTask extends TimerTask{//继承TimerTask类
public void run(){
System.out.println("printing!");
}
}这样这个程序就会在五秒钟后输出 printing!
Timer的功能是相当强大的,若要详细了解,可以查看帮助文档.
完整案例!
现在大家看一下我写的关于实现LED滚屏显示动态信息!
web 监听:
Java代码
package com.ving.xzfw.led;
import java.util.Timer;//定时器类
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.ServletContext;
import org.apache.log4j.Logger;
import com.ving.xzfw.util.GetInformation;
//import com.ving.xzfw.lwsp.GetConfigInfor;
public class LEDListener implements ServletContextListener {
private Timer timer = null;
private Logger log = Logger.getLogger(getClass());
// GetconfigInfor config = new GetconfigInfor();
GetInformation getInfo = new GetInformation("bpelConfig.properties");
Integer runTime = Integer.parseInt(getInfo.getProperty("led.TimingRunTime"));
String fileRealPath = "";
String templePath = "";
public void contextInitialized(ServletContextEvent event) {
// 在这里初始化监听器,在tomcat启动的时候监听器启动,可以在这里实现定时器功能
ServletContext context = event.getServletContext();
fileRealPath = context.getRealPath("")
+ System.getProperty("file.separator") + "LEDFile"
+ System.getProperty("file.separator");
templePath = context.getRealPath("")
+ System.getProperty("file.separator") + "led"
+ System.getProperty("file.separator");
timer = new Timer();
log.info("定时器已启动");// 添加日志,可在tomcat日志中查看到
timer.schedule(new LEDTimerTack(fileRealPath, templePath), 20000, runTime);
log.info("已经添加任务");
}