Search code examples
javaloggingwindows-servicesfilehandler

Closing Java FileHandler when quitting a routine that runs as a service


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?


Solution

  • 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