Showing posts with label timer. Show all posts
Showing posts with label timer. Show all posts

Sunday, 19 June 2011

Java has a nanosecond timer!

Java has a nanosecond timer!

It works well too.

Quick test script:

We do empty loops of varying numbers of iterations, and use the nanotimer to test how long that takes:

for( int its = 0; its < 100; its++ ) {
long start = System.nanoTime();
for( int i = 0; i < its; i++ ) {
}
long delta = System.nanoTime() - start;
System.out.println("its " + its + ": " + delta );
}

Saturday, 30 April 2011

Java timer test

Example to show java timer:

import java.util.Calendar;
import java.util.Timer;
import java.util.TimerTask;

public class TestTimerTask {
public static void main(String[] args) { 
//define a timer 
final Timer timer = new Timer("Test Timer"); 
 
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
System.out.println("Timer fired");
}
}, Calendar.getInstance().getTime(), 5 * 1000);

Runtime.getRuntime().addShutdownHook(new Thread() {
public void run() {
System.out.println("Canceling timer");
timer.cancel();
}
});
}
}