How to use Timer class to call a method, do something, reset timer, repeat?

前端 未结 5 998
离开以前
离开以前 2020-11-28 08:33

I\'m a Java beginner and have been futzing around with various solutions to this problem and have gotten myself kind of knotted up. I\'ve tried with Threads and then discove

5条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-28 09:17

    Do you specifically want a Timer? If not you're probably better off with a ScheduledExecutorService and calling scheduleAtFixedRate or scheduleWithFixedDelay; quoting the Javadocs:

    Java 5.0 introduced the java.util.concurrent package and one of the concurrency utilities therein is the ScheduledThreadPoolExecutor which is a thread pool for repeatedly executing tasks at a given rate or delay. It is effectively a more versatile replacement for the Timer/TimerTask combination, as it allows multiple service threads, accepts various time units, and doesn't require subclassing TimerTask (just implement Runnable). Configuring ScheduledThreadPoolExecutor with one thread makes it equivalent to Timer.

    UPDATE

    Here's some working code using a ScheduledExecutorService:

    import java.util.Date;
    import java.util.concurrent.Executors;
    import java.util.concurrent.ScheduledExecutorService;
    import java.util.concurrent.TimeUnit;
    
    public class Test {
        public static void main(String[] args) {
            final ScheduledExecutorService ses = Executors.newSingleThreadScheduledExecutor();
            ses.scheduleWithFixedDelay(new Runnable() {
                @Override
                public void run() {
                    System.out.println(new Date());
                }
            }, 0, 1, TimeUnit.SECONDS);
        }
    }
    

    The output looks like:

    Thu Feb 23 21:20:02 HKT 2012
    Thu Feb 23 21:20:03 HKT 2012
    Thu Feb 23 21:20:04 HKT 2012
    Thu Feb 23 21:20:05 HKT 2012
    Thu Feb 23 21:20:06 HKT 2012
    Thu Feb 23 21:20:07 HKT 2012
    

提交回复
热议问题