0

I have a little routine that schedules a timer like that:

timer.schedule(new myRoutine(), 1000, 60000);

In the run() method of myRoutine a logger is opened and a FileHandler is attached to it:

FileHandler fh = new FileHandler("app.log"),true);
logger.addHandler(fh);

Since there is no real exit point to the application (as it runs as a service), i have no chance to close and remove the logger´s FileHandler, hence the file lock (app.log.lck) remains, resulting in a new logfile (app.log.1) on next start of the service.

Is there a way to ensure the FileHandler is closed and removed?

Vladimir Vagaytsev
  • 2,871
  • 9
  • 33
  • 36
Prefect73
  • 321
  • 3
  • 14

2 Answers2

0

Maybe I am blind, but why don't you do something like:

class MyRoutine {
  public void run() {
    FileHandler fh = null;
    try {
      fh = ...
      whatever else to do ...
    } finally { 
      cleanup fh }

Or, maybe, just go for try-with-resource?

You know, even when myRoutine (wrong casiness there, by the way) is a "service"; don't you expect it to be called, do something and then go away?

GhostCat
  • 137,827
  • 25
  • 176
  • 248
0

You could add shutdown hook like this:

In a method that schedules timer:

public void scheduleFileTask() {
    final FileHandler fh = new FileHandler("app.log"),true);
    Runtime.getRuntime().addShutdownHook(new Thread() {
        @Override
        public void run() {
            fh.close();
        }
    });
    timer.schedule(new MyRoutine(fh), 1000, 60000);
}

And in MyRoutine.java

public class MyRoutine extends TimerTask {
    private final FileHandler handler;

    public MyRoutine(FileHandler hander) {
        this.handler = handler;
    }

    public void run() {
        // use handler here 
        handler.doSomething();
    }
}

For more information you can look up java docs

river
  • 774
  • 5
  • 16
  • When I do it that way, the TimerTask can´t "see" the run() method any more and therefore gives a compiler error: "must implement run()" – Prefect73 Jul 04 '16 at 16:34
  • You should pass resource to your task. I just edited answer to demonstrate that. – river Jul 04 '16 at 18:31
  • Thanks for your support, but i don´t get what you mean. The run() method needs to reside in the class that is scheduled by the timer which itself needs to inherit from TimerTask. But in this case, the run() method cannot be wrapped by the Runtime.getRuntime(). – Prefect73 Jul 05 '16 at 07:46
  • Ok, forget it. I obviously confused the Hook´s run() method with the Timer´s run() method. The Shutdown hook is nevertheless the technique of choice here. – Prefect73 Jul 05 '16 at 12:21