• Post Reply Bookmark Topic Watch Topic
  • New Topic

Timer class for an Alarm?  RSS feed

 
omar elgazzar
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi, I want to create an alarm application, and after some searching I found that java.util.Timer class may be useful.
But when I checked the Java API, It says 'no real-time guarantees' !!
What does this mean? Does it mean that it will be inaccurate ??
So, is it a good idea to use Timers or there's another alternative ??
 
Campbell Ritchie
Marshal
Posts: 56541
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
How precise do you require the timer to be?
 
omar elgazzar
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Campbell Ritchie wrote:How precise do you require the timer to be?

I want to know the most precise way
 
Tim Moores
Saloon Keeper
Posts: 4032
94
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The standard JVM is not realtime capable, so nothing is guaranteed to happen at precise moments in time. Having said that, Timer and TimerTask are very useful classes, and I would be surprised if they deviated even a full second from their intended alarm time.
 
Campbell Ritchie
Marshal
Posts: 56541
172
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
omar elgazzar wrote:. . . I want to know the most precise way
So how little an error will you tolerate when the alarm warns you to do something? 1nanosecond? 1μs? 1ms? I think you will find that all contemporary computers' clocks are accurate to the nearest ms (I hope I am right ‍), though 20 years ago you might only have got 0.1s precision.
 
omar elgazzar
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I've come up with this code [Preliminary Code], what do you think ?

 
Stephan van Hulst
Saloon Keeper
Posts: 7987
143
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A few things Omar,

  • Make your class final.
  • Use java.time.LocalTime instead of java.util.Calendar.
  • Use java.util.concurrent.ScheduledExecutorService instead of java.util.Timer.
  • Use java.time.format.DateTimeFormatter instead of String.format().
  •  
    Don't get me started about those stupid light bulbs.
    • Post Reply Bookmark Topic Watch Topic
    • New Topic
    Boost this thread!