I would like to run a method every 1 ms in a timespan of 5 sec. Right now i am using
long t = System.currentTimeMillis(); long end = t + 5000; while (System.currentTimeMillis() < end) { // do something // pause to avoid churning try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } }
The problem with this code is that it freezes the UI in the 5 sec timespan. Which I’m not interested in. Can a runnable or handler be used instead, and then terminated after 5 sec ? Regards!
Advertisement
Answer
You can use Handler#postDelayed
recursively:
private void doTask(long endTimeMillis) { // do something long now = System.currentTimeMillis(); if (now < endTimeMillis) { new Handler(Looper.getMainLooper()).postDelayed(() -> { doTask(endTimeMillis); }, 1L); } }