Making a program run for 5 minutes

前端 未结 5 2100
隐瞒了意图╮
隐瞒了意图╮ 2021-01-26 14:03

So I wanted to try out something for a bit with the Timer and TimerTask classes.

I was able to get a line of code to execute after 30 seconds elapsed. What I\'ve been t

5条回答
  •  梦谈多话
    2021-01-26 14:15

    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.

    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
    );
    

提交回复
热议问题