Java / Android Programming - Loop FAIL

后端 未结 3 451
温柔的废话
温柔的废话 2021-01-29 14:39

I am using a while loop with a timer. The thing is that the timer is not used in every loop. It is used only the first time. After the first time the statements included inside

相关标签:
3条回答
  • 2021-01-29 15:20

    The TimerTask kicks off a new Thread and then the loop proceeds as normal.

    The execution of the thread does not cause a delay to the execution of the code in your loop.

    0 讨论(0)
  • 2021-01-29 15:20

    You're scheduling 10 TimerTasks to execute after an hour, at the same time. So all 10 tasks are being executed after 1 hour, which makes it seem like 1 execute since all the Toast messages display at the same time. To schedule tasks at a fixed delay, with the first task starting in 1 hour, use this method:

    Timer t = new Timer();
    t.schedule(task, 3600000, 3600000);
    

    This will execute until you call t.cancel().

    0 讨论(0)
  • 2021-01-29 15:36

    It's because you're queueing up 10 toasts all to execute in one hour. Each iteration of your loop takes only a fraction of a millisecond or maybe a tad bit more than that. To enqueue them properly, you could do 3600000 * count instead of 3600000 each time.

    This is a terrible way to do it though. You should use AlarmManager for stuff like this.

    0 讨论(0)
提交回复
热议问题