我在使用timer来定时执行一个任务时,方法如下:
timer.scheduleAtFixedRate(task, firstTime, period)
需求如下:
    task为一个生成文件的任务,首次执行任务时间firsttime为当前时间的下一个半点,比如现在时13:20,执行时间就为13:30,周期为30*60*1000,每半小时执行一次task出现的bug:
    在系统繁忙时,在正常执行一段时间后,会出现每秒钟都执行多次任务,就是run方法被多次调用了,导致文件每秒钟都有生成。可从打出来的log看,period还是30*60*1000,没有错。个人疑问:timer是否存在bug。

解决方案 »

  1.   

    楼主怎么只提问题不结贴呀
    不要动不动就说是人家的问题,先看看人家的说明、自己的用法
    看看传参是否有误
    或许,是你调用的TimerTask 内实现的有问题
    贴点代码出来public void scheduleAtFixedRate(TimerTask task,
                                    Date firstTime,
                                    long period)Schedules the specified task for repeated fixed-rate execution, beginning at the specified time. Subsequent executions take place at approximately regular intervals, separated by the specified period. 
    In fixed-rate execution, each execution is scheduled relative to the scheduled execution time of the initial execution. If an execution is delayed for any reason (such as garbage collection or other background activity), two or more executions will occur in rapid succession to "catch up." In the long run, the frequency of execution will be exactly the reciprocal of the specified period (assuming the system clock underlying Object.wait(long) is accurate). Fixed-rate execution is appropriate for recurring activities that are sensitive to absolute time, such as ringing a chime every hour on the hour, or running scheduled maintenance every day at a particular time. It is also appropriate for for recurring activities where the total time to perform a fixed number of executions is important, such as a countdown timer that ticks once every second for ten seconds. Finally, fixed-rate execution is appropriate for scheduling multiple repeating timer tasks that must remain synchronized with respect to one another. Parameters:
    task - task to be scheduled.
    firstTime - First time at which task is to be executed.
    period - time in milliseconds between successive task executions. 
      

  2.   

    使用scheduleAtFixedRate的时候,如果因为系统繁忙或者垃圾回收等原因,导致task没有被执行,task将会很快连续执行.
      

  3.   

    要看你的TimerTask的设置情况。在间隔时间到来时,你的任务如果还没有处理完,又开始执行新任务,就会出现问题。所以你要配置scheduleAtFixedRate
      

  4.   

    If an execution is delayed for any reason (such as garbage collection or other background activity), two or more executions will occur in rapid succession to "catch up." 不知道生成文件的任务要多久,估计就是发生了帮助文档讲的这种情况.