mchrobok
mchrobok

Reputation: 2027

Cancelling a timer

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

Answers (2)

Jarek Potiuk
Jarek Potiuk

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:

  • store log entry
  • check if you have a timer task waiting to be executed (one boolean volatile 'taskRunning' flag). If not - fire task with 30 seconds delay, but only ONCE (not repetitive) and set the taskRunning flag to true. If flag is set to true - do nothing.
  • in your timer task: clear the 'taskRunning' flag, write all the logs stored so far and ... do not fire another task. No need. Whenever someone writes log file, it will start another task which will write logs 30 secs after.

Note. In order to avoid races you need some synchronisation on log read/write as well.

Upvotes: 1

MJB
MJB

Reputation: 9399

A shutdown hook is the way. Read the caveats, and description here. Also consider this for a prewritten log to file for android solution

Upvotes: 1

Related Questions