How to execute long-running tasks?

java, multithreading

Solution

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.

Problem

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?

Original source