Programming Tips - How can efficiently and accurately run code at a regular interval?

Date: 2015feb3 Language: Java Keywords: Android, setInterval() Q. How can efficiently and accurately run code at a regular interval? A. Use ScheduledExecutorService.
Runnable runnable = new Runnable { @Override public void run() { // Do something every 100 ms } } ScheduledExecutorService ses = Executors.newScheduledThreadPool(1); ScheduledFuture<?> handle = ses.scheduleAtFixedRate(runnable, 0, 100, TimeUnit.MILLISECONDS);
// If you want to stop handle.cancel(true); // Can be done inside run() or elsewhere // If you want to wait for it to finish handle.get();