简体   繁体   中英

Which to use Timer or ThreadPool in java?

我在Java中有一个应用程序,需要安排命令在给定的延迟后运行,我应该使用Timer或ThreadPool,为什么?

I'd recommend that you use a ScheduledExecutorService . Rationale: it is much easier to use than Timer or TimerTask .

You can obtain one using, for instance, Executors.newScheduledThreadPool() .

If you are using Spring, another solution is @Scheduled . Simply annotate a desired method with that annotation and specify the delay or a certain time at which you want to be called. The advantage is that you do not need a new class implementing Runnable and concern yourself with multiple thread (although Executors frameworks is easy to use). But you need the class having the method with the annotation to be a Spring Bean; also the method needs to return void and have no arguments.

It's actually this simple:

@Scheduled(fixedRate = 5000)//the method is called once every 5 seconds
public void myScheduledMethod() {
    //do you stuff
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM