3

Said now is 6 o'clock, I have a Timer and scheduled a TimerTask at 10 o'clock. After that, System DateTime is adjusted by an other service (ntp for example) to 9 o'clock. I still want my TimerTask will be fired at 10 o'clock but it does not, Timer still wait for next 4 hours and fire my TimerTask. What should I do in this situation?

secmask
  • 7,649
  • 5
  • 35
  • 52

1 Answers1

3

Firstly, you're already in a pretty nasty mess if your clock is out by 4 hours. Typically time adjustments will only be by milliseconds or seconds - or occasionally a minute or two, if the machine hasn't been online for a very long time. One option would be to check that the time is reasonably accurate by making your own NTP call before setting the timer.

Another option is to make a reasonably regularly-invoked timer - for example once every minute or five minutes - which checks the time and then optionally takes action. It's slightly less efficient, but I wouldn't expect the impact of waking up a single thread to perform a simple check once a minute or so would have a significant effect on performance. You should adjust the regularity of the check based on how accurately you need your timer to fire, and how little performance impact you need it to have.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • that's number just as an example. Thing that I think about is behavior of Timer when SystemTime changed. – secmask Aug 20 '11 at 07:50
  • @secmask: So why give such an unlikely example? You should also tell us how important it is that your task executes close to the desired time - what margin of error you have, etc. – Jon Skeet Aug 20 '11 at 07:52
  • I have a TimerTask that needed to fired at a time(physical time, such as result of new Date()+ x_hours), but when someone change system time, my TimerTask does not fire at that time-point, but later or sooner. And I think it make me(and some peoples) confused. – secmask Aug 20 '11 at 07:58
  • 1
    @secmask: That doesn't answer what the margin for error is. Is checking once a minute good enough? Obviously if someone changes the system time from 1pm to 5pm and you were meant to fire at 3pm, then you're clearly *not* going to be able to fire at 3pm because it basically didn't exist. What would you *want* to do in that case? – Jon Skeet Aug 20 '11 at 08:04
  • yep, using of loop and check is ok. – secmask Aug 20 '11 at 10:22