我需要运行以下代码仅60秒
代码工作完美,延迟2秒,每5秒重复一次..
但在这里我只需要60秒才能完成这项工作
int delay = 3000; // delay for 3 sec.
int period = 5000; // repeat every 5 sec.
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
System.out.println("Would it run?"+System.currentTimeMillis());
}
}, delay, period);
请告诉我怎么做?
答案 0 :(得分:7)
您只需使用a ScheduledExecutorService
:
ScheduledFuture
final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
final Runnable task = new Runnable() {
public void run() {
System.out.println("Would it run?"+System.currentTimeMillis());
}
};
final ScheduledFuture<?> handle =
scheduler.scheduleAtFixedRate(task, 2, 5, TimeUnit.SECONDS);
scheduler.schedule(new Runnable() {
public void run() { handle.cancel(true); }
}, 60, SECONDS);
答案 1 :(得分:1)
public class test{
static int delay = 3000; // delay for 3 sec.
static int period = 5000; // repeat every 5 sec.
static int totaltime = 0;
public static void main(String ar[]){
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
test.totaltime+= ((test.delay+test.period)/1000);
if(test.totaltime > 60)System.exit(0);
System.out.println("Would it run?"+System.currentTimeMillis());
}
}, test.delay, test.period);
}
}
答案 2 :(得分:1)
你需要计算你做过多少次,然后取消:
import java.util.Timer;
import java.util.TimerTask;
public class Waiting {
public static int times;
public static void main(String[] args)
{
int delay = 3000; // delay for 3 sec.
int period = 5000; // repeat every 5 sec.
times = 60000 / ( delay + period );
Timer timer = new Timer();
timer.scheduleAtFixedRate( new TimerTask() {
public void run() {
System.out.println( "Times remaining: " + Waiting.times );
--Waiting.times;
if ( Waiting.times == 0 ) {
this.cancel();
System.exit( 0 );
}
}
}, delay, period);
}
}
希望这有帮助。
答案 3 :(得分:0)
您可以设置一个定时器,该定时器将设置为60并设置如下:
int time = 3;
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
if(time<60){
System.out.println("Would it run?"+System.currentTimeMillis());
time = time + 5;
}
else{ timer.stop(); }
}
}, delay, period);
答案 4 :(得分:0)
在所需的重复次数后,只需从cancel
方法调用run
即可。
答案 5 :(得分:0)
老实说,我从未使用过计时器,但如果你想在一段时间内运行你的任务,为什么不使用public void schedule(TimerTask task,long delay, long period)
如果我没有正确解读,你现在想要运行你的任务,持续60秒,所以:
timer.schedule(myTask,0,60000);
应该为你做,但正如我所说,我从不与定时器合作,所以我不是百分百肯定它会起作用