0

I'm using the SchduledExecuterService class to run some code repeatedly using the scheduleAtFixedRate() method.

exec.scheduleAtFixedRate(new Runnable() {
    public void run() {
        //some code
    }
}, 1, 1, TimeUnit.SECONDS);

The problem is that I want to alter the TimeUnit argument to be a certain fraction of a second, depending on a variable, i.e. TimeUnit.SECONDS*num; But the method doesn't take longs as parameters, only fixed TimeUnits. Any suggestions?

Raptor_Guy
  • 9
  • 1
  • 4
  • The `1` and `1` are the initial delay and period, respectively. If you want to use `num` as the initial delay, replace the first one. If you want something smaller than a second, use a finer unit, e.g. `TimeUnit.MILLISECONDS`. – Andy Turner Oct 08 '19 at 15:00
  • I don't understand your question. `scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit)` -> takes `long` as argument and `TimeUnit` can be `MILLISECONDS` as well (500 milliseconds = 1/2 second) – GameDroids Oct 08 '19 at 15:01

1 Answers1

1

Why don't you play with period parameter ?

long periodInMicroseconds = 16667;
exec.scheduleAtFixedRate(new Runnable() {
    public void run() {
        //some code
    }
}, 0, periodInMicroseconds, TimeUnit.MICROSECONDS);
Jonathan
  • 127
  • 1
  • 11
  • 1
    That will approximate 1/60 of a second quite nicely. To make this fact clearer in the code we might write `Math.round(1_000_000.0 / 60.0)` or even `Math.round(TimeUnit.SECONDS.toMicros(1) / 60.0)`. – Ole V.V. Oct 08 '19 at 15:05
  • 1
    It was an example but you are right. (I prefer your second option). – Jonathan Oct 08 '19 at 15:15