Assume I've timer task running and creates a new resource on load as demonstrated below. It's a monitoring process set to run indefinitely and is invoked from inside the jar.
For example.
Main Class
public class MyMain {
public static void main(String[] args ) {
TimerTask task = new MyTimerTask();
Timer timer = new Timer();
timer.scheduleAtFixedRate(task,0,30000)
}
}
Timer Task
class MyTimerTask extends TimerTask {
private static final MyResource resource;
static {
resource = new MyResource();
}
@Override
public void run() {
....
}
public void close() {
resource.close();
}
}
Question: When I stop the process using command line I would like to make sure the resource close method is called. What changes do I need to make ?
I have looked at current solutions ranging from shutdown hook to JMX but I can't decide which one to go with. As I read all solutions it looks to me there is not a clean solution for shutting down the resources in this setup but would like to know the preferred way.
Let me know if you need further details.