开发者

Schedule multiple tasks in a single thread

开发者 https://www.devze.com 2023-03-10 14:03 出处:网络
I want to have a single thread maintain responsibility for multiple tasks scheduled at different intervals. I want to add and remove tasks from the scheduler. Are there any libraries that can help me

I want to have a single thread maintain responsibility for multiple tasks scheduled at different intervals. I want to add and remove tasks from the scheduler. Are there any libraries that can help me with this. If not I will code my own just don't want to reinvent the wheel.

For background I want to add alerting to my application, controlled from a single thread where the rest of the application can add/remove scheduled tasks. I can use multiple T开发者_如何学JAVAimerTask's or write my own single threaded scheduler but if there is better option I don't want to overlook it.

James


If you need something that's available right out of the box in JDK 1.5 or later, have you looked at ScheduledExecutorService?

http://download.oracle.com/javase/6/docs/api/java/util/concurrent/ScheduledExecutorService.html

You can create one of these, backed by a single thread, using this factory method:

http://download.oracle.com/javase/6/docs/api/java/util/concurrent/Executors.html#newSingleThreadScheduledExecutor()

There's also an alternative factory method that accepts a ThreadFactory as an argument. This gives you an opportunity to customize the Thread that will run inside the ScheduledExecutorService. For example, you can call Thread.setName to give the thread a more meaningful name. This is very helpful for debugging an application. When you generate a full thread dump, you'll see your custom name attached to the thread instead of a generic name attached automatically by the JVM.

Depending on the need, it might also be appropriate to call Thread.setDaemon(true), so that this thread won't block JVM shutdown.

Also, it's best practice to clean up any ExecutorService after you're done with it by calling ExecutorService.shutdown or ExecutorService.shutdownNow. Without a guaranteed call to shutdown (such as in a finally block), it's possible to introduce a thread leak bug in your application. From the usage you describe, it sounds unlikely that this will bite you, but I always like to stress this when I give someone a recommendation to use an ExecutorService. It's easy to miss this point from the JavaDocs.


If you want a basic library, you can use the built in ScheduledExecutorService. This allows to add repeating tasks and cancel them. You can set it to be single threaded.


Check out Quartz. It's pretty much the go-to for task scheduling in Java. You can configure it to be single-threaded if you poke through the docs.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号