我想每秒执行一次方法20次.
其实我有计时器
Timer timer = new Timer();
int begin = 0;
int timeInterval = 1000;
timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
//call the method
}
}, begin, timeInterval);
Run Code Online (Sandbox Code Playgroud)
如何以此间隔调用方法20次?
使用timer.schedule(),并跟踪计时器执行的次数,并在20次后停止计时器timer.cancel()
在指定的延迟之后开始,为重复的固定延迟执行安排指定的任务.随后的执行大约以规定的时间间隔进行,并以指定的时间段分隔.
在固定延迟执行中,每次执行都是相对于上一次执行的实际执行时间进行调度的.如果执行因任何原因(例如垃圾收集或其他后台活动)而延迟,则后续执行也将延迟.从长远来看,执行频率通常会略低于指定时间段的倒数(假设Object.wait(long)下的系统时钟是准确的).
固定延迟执行适用于需要"平滑"的重复活动.换句话说,它适用于在短期内保持频率比长期更准确的活动.这包括大多数动画任务,例如定期闪烁光标.它还包括响应于人类输入而执行常规活动的任务,例如只要按下键就自动重复一个字符.
参数:
Run Code Online (Sandbox Code Playgroud)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);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2516 次 |
| 最近记录: |