• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
mark_xiao
博客园    首页    新随笔    联系   管理    订阅  订阅

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)才是重复的执行。

 

posted @ 2015-10-20 16:16  mark_xiao  阅读(729)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3