Ankur
Ankur

Reputation: 51118

How to create a Java timer that repeats at different times

I have some stock market data. I want to simulate the stock market by having prices sent at intervals that can be determined from the times at which trades occur.

What would the best way be to do this.

So far I have a class with static variables and methods in which I am storing the hour, min, millseconds for the last trade time. I then use the trade time for the current trade and calculate it from the stored last trade values.

I then store as a static member variable the "interval" in milliseconds in the same class as the time variables are stored.

I use this line:

timer.schedule(new RemindTask(), TimeStore.getNextInterval());

where TimeStore.getNextInterval() retrieves the interval that was calculated.

Can you think of a better way, this doesnt seem to work, nor does it seem very elegant.

Upvotes: 2

Views: 1567

Answers (3)

Gunjan Nigam
Gunjan Nigam

Reputation:

Well For Your Task I have a different Solution. You can use javax.swing.Timer instead of java.util.Timer; and then u can call the constructor by sending the delay which u want and null for action actionListeners and then you can add and addactionListeners(this) and override actionPerformed with ur task. In javax.swing.Timer the actionListeners are notified at selected interval repeatedly

Upvotes: -1

pjp
pjp

Reputation: 17639

If you don't want to go as far as using Quartz then look at Java's ScheduledExecutorService.

http://java.sun.com/javase/6/docs/api/java/util/concurrent/ScheduledExecutorService.html

Upvotes: 5

Alberto Zaccagni
Alberto Zaccagni

Reputation: 31590

Use Quartz.

From the linked page:

Quartz is a full-featured, open source job scheduling system that can be integrated with, or used along side virtually any J2EE or J2SE application - from the smallest stand-alone application to the largest e-commerce system. Quartz can be used to create simple or complex schedules for executing tens, hundreds, or even tens-of-thousands of jobs; jobs whose tasks are defined as standard Java components or EJBs. The Quartz Scheduler includes many enterprise-class features, such as JTA transactions and clustering.

Upvotes: 1

Related Questions