Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to execute long-running tasks?

Executors are usually used when it comes to (short-running) tasks, but what is the best way to deal with tasks that are long-running, e.g. tasks that should run throughout the lifetime of an application?

Let's say I have an application in which a task that runs on a separate thread polls a directory for changes every X seconds. This task should never quit polling, unless the application quits. How do I start and manage this?

Would new Thread(theLongRunningTask).start() be such a bad option?

like image 460
Cowboy Avatar asked May 14 '12 11:05

Cowboy


1 Answers

This is also a use-case for the Executors framework, specifically scheduleAtFixedRate. Just watch out for that thread hanging around when the app is done. You can use a custom ThreadFactory that makes daemon-threads. Or, if you want something simpler, use the Timer API. You can construct a Timer with a boolean argument meaning "use daemon thread". You can also shut down the executor service explicitly when your application is ending.

like image 104
Marko Topolnik Avatar answered Oct 11 '22 11:10

Marko Topolnik