`

Java计时器Timer 使用

阅读更多

所有类型的 Java 应用程序一般都需要计划重复执行的任务

Timer类是用来执行任务的类,它接受一个TimerTask做参数

java.util.Timer 和 java.util.TimerTask ,它们使程序员可以很容易地计划简单的任务

Timer

Timer最常用的是schedule执行任务的模式,,它可以以两种方式执行任务:

1:在某个时间(Data),2:在某个固定的时间之后(int delay).这两种方式都可以指定任务执行的频率.

看个简单的例子:

Java代码 复制代码
  1. importjava.io.IOException;
  2. importjava.util.Timer;
  3. publicclassTimerTest{
  4. publicstaticvoidmain(String[]args){
  5. Timertimer=newTimer();
  6. timer.schedule(newJob(),5000,10000);//在5秒后执行此任务,每次间隔60秒,如果传递一个Data参数,就可以在某个固定的时间执行这个任务.
  7. /*
  8. //这个是用来停止此任务的,否则就一直循环执行此任务了
  9. while(1==1){
  10. try{
  11. if(2==2){
  12. timer.cancel();//使用这个方法退出任务
  13. }
  14. }catch(IOExceptione)
  15. e.printStackTrace();
  16. }*/
  17. }
  18. staticclassJobextendsjava.util.TimerTask{
  19. @Override
  20. publicvoidrun(){
  21. //TODOAuto-generatedmethodstub
  22. System.out.println("so...easy!");
  23. }
  24. }
  25. }
  26. importjava.io.IOException;
  27. importjava.util.Timer;
  28. publicclassTimerTest{
  29. publicstaticvoidmain(String[]args){
  30. Timertimer=newTimer();
  31. timer.schedule(newJob(),5000,10000);//在5秒后执行此任务,每次间隔60秒,如果传递一个Data参数,就可以在某个固定的时间执行这个任务.
  32. /*
  33. //这个是用来停止此任务的,否则就一直循环执行此任务了
  34. while(1==1){
  35. try{
  36. if(2==2){
  37. timer.cancel();//使用这个方法退出任务
  38. }
  39. }catch(IOExceptione)
  40. e.printStackTrace();
  41. }*/
  42. }
  43. staticclassJobextendsjava.util.TimerTask{
  44. @Override
  45. publicvoidrun(){
  46. //TODOAuto-generatedmethodstub
  47. System.out.println("so...easy!");
  48. }
  49. }
  50. }
import java.io.IOException;

    import java.util.Timer;

    public class TimerTest {

    public static void main(String[] args){

    Timer timer = new Timer();

    timer.schedule(new Job(), 5000, 10000);//在5秒后执行此任务,每次间隔60秒,如果传递一个Data参数,就可以在某个固定的时间执行这个任务.

    /*

    //这个是用来停止此任务的,否则就一直循环执行此任务了

    while(1==1){

    try {

    if(2==2){

    timer.cancel();//使用这个方法退出任务

    }

    } catch (IOException e)

    e.printStackTrace();

    } */

    }

    static class Job extends java.util.TimerTask{

    @Override

    public void run() {

    // TODO Auto-generated method stub

    System.out.println("so...easy!");

    }

    }

    }

    import java.io.IOException;

    import java.util.Timer;

    public class TimerTest {

    public static void main(String[] args){

    Timer timer = new Timer();
timer.schedule(new Job(), 5000, 10000);//在5秒后执行此任务,每次间隔60秒,如果传递一个Data参数,就可以在某个固定的时间执行这个任务.

    /*

    //这个是用来停止此任务的,否则就一直循环执行此任务了

    while(1==1){

    try {

    if(2==2){

    timer.cancel();//使用这个方法退出任务

    }

    } catch (IOException e)

    e.printStackTrace();

    } */

    }

    static class Job extends java.util.TimerTask{

    @Override

    public void run() {

    // TODO Auto-generated method stub

    System.out.println("so...easy!");

    }

    }

    }

 

TimerTask 刚才在代码里提到了 TimerTask 类。TimerTask类里有一个抽象方法run(),我们把任务写到run()方法里,或由run()执行其他方法.

完整的代码:

Java代码 复制代码
  1. publicclassTimerTest{
  2. publicstaticvoidmain(String[]args){
  3. intdelay=5000;//延迟5秒
  4. Timertimer=newTimer();//生成一个Timer对象
  5. NewTaskmyTask=newNewTask();//初始化我们的任务
  6. timer.schedule(yourTask,delay);//还有其他重载方法...
  7. }
  8. }
  9. classNewTaskextendsTimerTask{//继承TimerTask类
  10. publicvoidrun(){
  11. System.out.println("printing!");
  12. }
  13. }
  14. publicclassTimerTest{
  15. publicstaticvoidmain(String[]args){
  16. intdelay=5000;//延迟5秒
  17. Timertimer=newTimer();//生成一个Timer对象
  18. NewTaskmyTask=newNewTask();//初始化我们的任务
  19. timer.schedule(yourTask,delay);//还有其他重载方法...
  20. }
  21. }
  22. classNewTaskextendsTimerTask{//继承TimerTask类
  23. publicvoidrun(){
  24. System.out.println("printing!");
  25. }
  26. }
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!");

    }

    }

    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代码 复制代码
  1. packagecom.ving.xzfw.led;
  2. importjava.util.Timer;//定时器类
  3. importjavax.servlet.ServletContextEvent;
  4. importjavax.servlet.ServletContextListener;
  5. importjavax.servlet.ServletContext;
  6. importorg.apache.log4j.Logger;
  7. importcom.ving.xzfw.util.GetInformation;
  8. //importcom.ving.xzfw.lwsp.GetConfigInfor;
  9. publicclassLEDListenerimplementsServletContextListener{
  10. privateTimertimer=null;
  11. privateLoggerlog=Logger.getLogger(getClass());
  12. //GetconfigInforconfig=newGetconfigInfor();
  13. GetInformationgetInfo=newGetInformation("bpelConfig.properties");
  14. IntegerrunTime=Integer.parseInt(getInfo.getProperty("led.TimingRunTime"));
  15. StringfileRealPath="";
  16. StringtemplePath="";
  17. publicvoidcontextInitialized(ServletContextEventevent){
  18. //在这里初始化监听器,在tomcat启动的时候监听器启动,可以在这里实现定时器功能
  19. ServletContextcontext=event.getServletContext();
  20. fileRealPath=context.getRealPath("")
  21. +System.getProperty("file.separator")+"LEDFile"
  22. +System.getProperty("file.separator");
  23. templePath=context.getRealPath("")
  24. +System.getProperty("file.separator")+"led"
  25. +System.getProperty("file.separator");
  26. timer=newTimer();
  27. log.info("定时器已启动");//添加日志,可在tomcat日志中查看到
  28. timer.schedule(newLEDTimerTack(fileRealPath,templePath),20000,runTime);
  29. log.info("已经添加任务");
  30. }
  31. publicvoidcontextDestroyed(ServletContextEventevent){//在这里关闭监听器,所以在这里销毁定时器。
  32. timer.cancel();
  33. log.info("定时器销毁");
  34. }
  35. }
  36. packagecom.ving.xzfw.led;
  37. importjava.util.Timer;//定时器类
  38. importjavax.servlet.ServletContextEvent;
  39. importjavax.servlet.ServletContextListener;
  40. importjavax.servlet.ServletContext;
  41. importorg.apache.log4j.Logger;
  42. importcom.ving.xzfw.util.GetInformation;
  43. //importcom.ving.xzfw.lwsp.GetConfigInfor;
  44. publicclassLEDListenerimplementsServletContextListener{
  45. privateTimertimer=null;
  46. privateLoggerlog=Logger.getLogger(getClass());
  47. //GetconfigInforconfig=newGetconfigInfor();
  48. GetInformationgetInfo=newGetInformation("bpelConfig.properties");
  49. IntegerrunTime=Integer.parseInt(getInfo.getProperty("led.TimingRunTime"));
  50. StringfileRealPath="";
  51. StringtemplePath="";
  52. publicvoidcontextInitialized(ServletContextEventevent){
  53. //在这里初始化监听器,在tomcat启动的时候监听器启动,可以在这里实现定时器功能
  54. ServletContextcontext=event.getServletContext();
  55. fileRealPath=context.getRealPath("")
  56. +System.getProperty("file.separator")+"LEDFile"
  57. +System.getProperty("file.separator");
  58. templePath=context.getRealPath("")
  59. +System.getProperty("file.separator")+"led"
  60. +System.getProperty("file.separator");
  61. timer=newTimer();
  62. log.info("定时器已启动");//添加日志,可在tomcat日志中查看到
  63. timer.schedule(newLEDTimerTack(fileRealPath,templePath),20000,runTime);
  64. log.info("已经添加任务");
  65. }
  66. publicvoidcontextDestroyed(ServletContextEventevent){//在这里关闭监听器,所以在这里销毁定时器。
  67. timer.cancel();
  68. log.info("定时器销毁");
  69. }
  70. }
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("已经添加任务");

    }

    public void contextDestroyed(ServletContextEvent event) {// 在这里关闭监听器,所以在这里销毁定时器。

    timer.cancel();

    log.info("定时器销毁");

    }

    }

    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("已经添加任务");

    }

    public void contextDestroyed(ServletContextEvent event) {// 在这里关闭监听器,所以在这里销毁定时器。

    timer.cancel();

    log.info("定时器销毁");

    }

    }

 

Java代码 复制代码
  1. packagecom.ving.xzfw.led;
  2. importjava.util.TimerTask;
  3. publicclassLEDTimerTackextendsTimerTask{
  4. StringfileRealPath="";
  5. StringtemplePath="";
  6. Stringtype="";
  7. intfloor;
  8. publicLEDTimerTack(StringfileRealPath,StringtemplePath,Stringtype,Integerfloor){
  9. this.fileRealPath=fileRealPath;
  10. this.templePath=templePath;
  11. this.type=type;
  12. this.floor=floor;
  13. }
  14. publicLEDTimerTack(StringfileRealPath,StringtemplePath){
  15. this.fileRealPath=fileRealPath;
  16. this.templePath=templePath;
  17. }
  18. publicvoidrun(){
  19. for(inti=1;i<=3;i++)
  20. //呵呵,这里就是led动态生成信息的代码!
  21. XlsUtil.createHtmlFile(templePath,fileRealPath,i);
  22. }
  23. }
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics