How to return the return value of the Runnable or Callable passed to ScheduledExecutorService.schedule

176 Views Asked by At
public Record task(Id id, Supplier<Record> elector) {
    // elector is: '() -> functionName(id, stats)'

    final long delayTime = calculateTimeToDelay();

    ScheduledExecutorService ses = Executors.newScheduledThreadPool(1);

    // Cannot resolve method 'schedule(Record, long, TimeUnit)'
    return ses.schedule(elector.get(), timeToDelay, TimeUnit.MILLISECONDS);

    // try {
    //     Thread.sleep(delayTime);
    // } catch (final InterruptedException e) {
    //     log.error(e);
    // }
    // return elector.get();
}

As you can see, the commented out code returns what elector.get() returns, which is a Record. But instead of using Thread.sleep(delayTime), I'm trying to use ScheduledExecutorService to call elector.get() after a few milliseconds of a delay. Not sure what Runnable and Callable is and whether elector.get() would count as one of those.

Some direction here would be appreciated.

1

There are 1 best solutions below

0
akarnokd On

ScheduledExecutorService.schedule requires a Callable so you'll have to convert your Supplier into a Callable, for example, via the method reference syntax:

ses.schedule(elector::get, timeToDelay, TimeUnit.MILLISECONDS);