我想执行的方法每秒20次。
其实我有计时器
Timer timer = new Timer();
int begin = 0;
int timeInterval = 1000;
timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
//call the method
}
}, begin, timeInterval);
我怎么能调用一个方法的20倍这个区间?
使用timer.schedule()
,并跟踪的定时器多少次被执行,20次后停止计时,用timer.cancel()
安排指定的任务进行重复的固定延迟执行,在指定的延迟后开始。后续执行发生在由指定的周期分隔大致规则的间隔。
在固定延迟执行,每个执行相对于前一次执行的实际执行时间调度。如果执行延迟因任何原因(如垃圾回收或其他背景活性),随后的执行将被延迟,以及。从长远来看,执行的频率一般会略低于指定周期(假定系统时钟底层的Object.wait(长)是准确)的倒数。
固定延迟执行适用于经常需要活动的“平滑度”。换句话说,它是适当的活动,它是保持准确的频率在短期内比在长期来看更为重要。这包括大多数动画任务,如以固定时间间隔闪烁的光标。它还包括其中响应于人类输入做股票任务,例如只要键被按下自动重复的字符。
参数:
task - task to be scheduled. delay - delay in milliseconds before task is to be executed. period - time in milliseconds between successive task executions.
Timer timer = new Timer();
int begin = 0;
int timeInterval = 1000;
timer.schedule(new TimerTask() {
int counter = 0;
@Override
public void run() {
//call the method
counter++;
if (counter >= 20){
timer.cancel();
}
}
}, begin, timeInterval);
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句