Reputation: 2027
I have a problem with a timer in my logger class. I created my own logger which should be as simple as it is possible - user can only call static log() method. Every call log() method causes that a log object (message, time, additional information) is adding to a list of logs.
When user calls this method first time, logger also starts a new Timer which saves all logs from a list to a file every 30seconds.
However, I don't have any idea where to call timer.cancel() method. I don't want to force user to do this in his code. Is it necessary to always cancel timer? Or this method is just to stop when user wants it.
Upvotes: 3
Views: 344
Reputation: 20107
But you do not need shutdown hook at all in this case. When VM is closed, all the threads will be cancelled anyway, and all open files will be closed, so no worries.
I believe what you want is to avoid the task waking continuously every 30 s even if app is not doing anything. I propose to do it a bit differently:
Whenever you log something in log method:
Note. In order to avoid races you need some synchronisation on log read/write as well.
Upvotes: 1