running loop for 5 minutes

前端 未结 3 1947
醉酒成梦
醉酒成梦 2021-01-14 22:10

I have a requirment to run a while loop the 5 min. I looked for the timer api but I could not found to do this. Can any one provide a code snipet for this.
Thanks

3条回答
  •  一生所求
    2021-01-14 23:05

    This loop will run for 5 minutes. It will not be effected by changes made to the computer's date/time (either by user or by NTP).

    long endTime = System.nanoTicks() + TimeUnit.NANOSECONDS.convert(5L, TimeUnit.MINUTES);
    while ( System.nanoTicks() < endTime ){
      // do whatever
    }
    

    Other methods like System.currentTimeMillis() should be avoided, because they rely on the computer date/time.

提交回复
热议问题