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

  • 相关阅读:
    IntelliJ IDEA基本设置
    git安装
    Git的作用与安装
    git是什么
    SpringMVC控制器类方法的返回值
    SpringMVC中Model机制
    什么是Nosql
    如何使用Jedis操作redis
    redis中数据类型操作命令
    redis的全局命令
  • 原文地址:https://www.cnblogs.com/kelina2mark/p/4895176.html
Copyright © 2020-2023  润新知