Dave's Brain

Browse - 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();

Add a comment

Sign in to add a comment
Copyright © 2008-2017, dave - Code samples on Dave's Brain is licensed under the Creative Commons Attribution 2.5 License. However other material, including English text has all rights reserved.