zoukankan      html  css  js  c++  java
  • TimerTask

    当TimerTask实例通过schedule方法使用之后,不能通过schedule方法调用第二次,如果重复使用就会抛异常TimerTask is scheduled already。

    当你重新想利用这个timertask时,那么你只能重新获得一个实例,最好是写成类:

    1  class MyTimerTask extends TimerTask{
    2     @Override
    3     public void run(){
    4         // TODO Auto-generated method stub
    5         //do something
    6     }
    7 };

    如果你再次使用TimerTask时,你可以这么做:

    1 task    = new MyTask();
    2 timer.schedule(task, 1000);

    对于这种只使用一次的timer,可以在使用完成之后停止它,新建一个timer意味着新建一个线程,不用了就销毁吧。

    1 timer.cancel();
    2 timer.purge();
    3 timer= null;

    每一次使用的时候

    1 timer    = new Timer();

    在重新new task之前,最好调用

    1 task.cancel();  //将原任务从队列中移除

    schedule(TimerTask task, long delay)的注释:Schedules the specified task for execution after the specified delay。大意是在延时delay毫秒后执行task。并没有提到重复执行

    schedule(TimerTask task, long delay, long period)的注释:Schedules the specified task for repeated fixed-delay execution, beginning after the specified delay。大意是在延时delay毫秒后重复的执行task,周期是period毫秒。

    这样问题就很明确schedule(TimerTask task, long delay)只执行一次,schedule(TimerTask task, long delay, long period)才是重复的执行。

  • 相关阅读:
    构建布局良好的Windows程序
    新认知之WinForm窗体程序
    分组查询之牛刀小试!
    Azure虚拟机时间同步问题
    关闭同一网络内的windows主机
    关于jdbc和数据库连接池的关系(不是封装的关系)
    spring,springMVC的优点和区别
    从新向你学习javase(第一天)
    spring包
    事物
  • 原文地址:https://www.cnblogs.com/kelina2mark/p/4895176.html
Copyright © 2011-2022 走看看