Aaron
Aaron

Reputation: 53

testing code on time interval

Hi I want to run code over a time period. For example i would like my code to do something like this.

for(every 5 minutes until i say to stop)
 automatically read in new value for x
 automatically read in new value for y

if (x==y)
     //do something

if (x!=y)
     //do something else

Upvotes: 1

Views: 609

Answers (4)

WhiteFang34
WhiteFang34

Reputation: 72039

How about:

Runnable runnable = new Runnable() {
    public void run() {
        // do your processing here
    }
};

ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
service.scheduleAtFixedRate(runnable, 0, 5, TimeUnit.MINUTES);

Call service.shutdown() when you want to stop.

Upvotes: 0

dominicbri7
dominicbri7

Reputation: 2599

System.currentTimeMillis(); Returns you the system time in milliseconds, you can use that. but first, you need some sort of loop. This is an alternative to Timer 's

public static final int SECONDS = 1000;
public static final int MINUTES = 60 * SECONDS;

boolean quit = false; //Used to quit when you want to..
long startTime = System.currentTimeMillis();

while (!quit) {
    if (System.currentTimeMillis() >= (startTime + (long)5*MINUTES)) {
        //automatically read in new value for x
         //automatically read in new value for y

        if (x==y) {
            //do something
        } else {
        //do something else
        }
        startTime = System.currentTimeMillis(); //reset the timer for the next 5 minutes
    }
}

Upvotes: 0

Erik
Erik

Reputation: 2051

Naive version. You might consider Timer or the quartz scheduler instead.

while (!done) {
   try {
     Thread.sleep(5 * 60 * 1000);
     x = readX();
     y = readY();
     if (x == y) {

     } else {

     }
   } catch(InterruptedException ie) {
   }
}

Upvotes: 0

Harry Joy
Harry Joy

Reputation: 59660

Timer is what you need.

Upvotes: 3

Related Questions