使程序运行5分钟 [英] Making a program run for 5 minutes
问题描述
所以我想尝试一下Timer和TimerTask类的一些东西。
So I wanted to try out something for a bit with the Timer and TimerTask classes.
我能够在30秒后获得一行代码来执行。
我现在要做的就是让这行代码执行5分钟。
I was able to get a line of code to execute after 30 seconds elapsed. What I've been trying to do now is to get this line of code to execute for 5 minuets.
这是我最初的尝试
public static void main(String[] args)
{
for ( int i = 0; i <= 10; i ++ )
{
Timer timer = new Timer();
timer.schedule( new TimerTask()
{
public void run()
{
System.out.println("30 Seconds Later");
}
}, 30000
);
}
}
我在for循环中使用数字10来查看如果timer.schedule在循环的下一次迭代期间再等30秒。
I used the number 10 in the for loop to see if the timer.schedule would wait for another 30 seconds during the next iteration of the loop.
任何想法我应该怎么做?我尝试使用schedule方法传入一段时间的参数,但这只是让它重新执行并且它永远不会停止。
Any idea how I should go about this? I tried using the schedule method with a parameter passed in for period, but that only made it re-execute and it never stopped.
推荐答案
您遇到的问题是计划的计时器
在另一个线程上运行 - 也就是的下一次迭代
循环在调度后立即开始运行,而不是30秒后。看起来你的代码一次启动十个计时器,这意味着它们应该在30秒后全部打印,一次全部打印。
The issue you're running into is that the scheduled Timer
runs on a different thread - that is, the next iteration of your for
loop starts running immediately after scheduling, not 30 seconds later. It looks like your code starts ten timers all at once, which means they should all print (roughly) 30 seconds later, all at once.
你走在正确的轨道上当您尝试使用定期版本的 schedule
(使用第三个参数)时。如你所知,这不是你想要的,因为它无限期地运行。但是,计时器
有一个取消
方法,以防止后续执行。
You were on the right track when you tried using the recurring version of schedule
(with the third parameter). As you noted, this isn't quite what you want because it runs indefinitely. However, Timer
does have a cancel
method to prevent subsequent executions.
所以,你应该尝试类似的东西:
So, you should try something like:
final Timer timer = new Timer();
// Note that timer has been declared final, to allow use in anon. class below
timer.schedule( new TimerTask()
{
private int i = 10;
public void run()
{
System.out.println("30 Seconds Later");
if (--i < 1) timer.cancel(); // Count down ten times, then cancel
}
}, 30000, 30000 //Note the second argument for repetition
);
这篇关于使程序运行5分钟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!