14

Basically I want a function to be called every say, 10 milliseconds.

How can I achieve that in Java?

Jonas
  • 121,568
  • 97
  • 310
  • 388
hasen
  • 161,647
  • 65
  • 194
  • 231

5 Answers5

17

You might want to take a look at Timer.

Bombe
  • 81,643
  • 20
  • 123
  • 127
10

Check out java.util.Timer

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

jishi
  • 24,126
  • 6
  • 49
  • 75
4

You could also use a ScheduleExecutorService.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
2

I would say you would create a thread and in the thread loop add a System.sleep(10) to make the thread "sleep" for 10 ms before continuing.

Ravi Wallau
  • 10,416
  • 2
  • 25
  • 34
0

Using ExecutorService

    ScheduledExecutorService es = Executors.newSingleThreadScheduledExecutor();
    es.scheduleAtFixedRate(() -> System.out.println("Hello World! from ScheduledExecutorService"), 10000, 10000, TimeUnit.MILLISECONDS);
    //es.shutdown();

Or by using Timer

    Timer timer = new Timer();
    timer.scheduleAtFixedRate(new TimerTask() {
        @Override
        public void run() {
            System.out.println("Hello World! from Timer");
        }
    }, 10000, 10000);
    //timer.cancel();

Cheers!

Mohan
  • 4,755
  • 2
  • 27
  • 20