5

I have a Java EE application which downloads stock prices from the internet every fifteen minutes. From a timing accuracy perspective is is best for the application to internalise this periodic operation i.e. use Thread.sleep() in combination with a counter or set up a timer Or would it be better to expose the task via a URL and have a platform cron job hit the URL periodically (at the the required frequency of course).

What are the pros and cons of both approaches?

I've been spooked by a timer bug I saw reported against the OpenJDK implementation. The bug stated that changes in the system time affected the operation of the time related operations and methods such as sleep and timer periodicity.

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555

3 Answers3

2

Timer is not deprecated, but a better alternative now exists: SheduledExecutorService. One of what makes it better is that it uses relative time rather than absolute time for scheduling.

Using an external cron script or an internal timer is just a matter or preference, IMHO. An internal timer is easier to setup, but if you already have other crons in place, you might want to use an additional one and have this responsibility in a single place.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
1

Thread.sleep is not a recommended way to execute code periodically. It's inaccurate and usually a sign of bad design. I suggest you use the Timer class to easily schedule the execution of code periodically.

Tudor
  • 61,523
  • 12
  • 102
  • 142
1

Definitely consider using a scheduling job that was built for the task. Try and split the task itself from any timing considerations.

  • As was suggested, Quartz is a good choice.
  • Cron is not bad, but would require more setup to integrate with your task.
  • If on Java EE you can use an EJB timer.
  • You can roll your own with ScheduledExecutorService (not recommended)
Arjan Tijms
  • 37,782
  • 12
  • 108
  • 140
Perception
  • 79,279
  • 19
  • 185
  • 195