Run code every second by using System.currentTimeMillis()

后端 未结 5 959
滥情空心
滥情空心 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

    I'd use the java executor libraries. You can create a ScheduledPool that takes a runnable and can run for any time period you want. For example

    Executors.newSingleThreadScheduledExecutor().scheduleAtFixedRate(new MyRunnable(), 0, 5, TimeUnit.SECONDS);
    

    Will run the MyRunnable class every 5 seconds. MyRunnable must implement Runnable. The trouble with this is that it will (efficiently) create a new thread each time which may or may not be desirable.

提交回复
热议问题