Run code every second by using System.currentTimeMillis()

后端 未结 5 968
滥情空心
滥情空心 2021-02-07 14:52

I am trying to run a line of code every second by using System.currentTimeMillis();.

The code:

     while(true){
           long var = System.currentTim         


        
5条回答
  •  礼貌的吻别
    2021-02-07 15:40

    preferred way:

    ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
    

    Then pass in Runnables like:

    scheduler.scheduleWithFixedDelay(myRunnable, initDelay, delay, TimeUnit.MILLISECONDS);
    

    I wouldn't use the Timer. Schedulers are built to handle problems that Timers can cause. Also, the Thread.sleep is good for a simple program that you're writing quickly for proof of concept type things but I wouldn't use it in the enterprise world.

提交回复
热议问题