Tyler
Tyler

Reputation: 23

How to run tasks at a scheduled rate that DON'T wait for the task before it?

Currently, I have some code that I need to run every (for example) 33 milliseconds. However, the operation that I am calling requires around 270ms. Is there a way to schedule my tasks so that they run regardless of the task before them?

I have tried implementing a ScheduledExecutorService variable and running the task at a "ScheduledFixedRate" but that currently waits for the task before it.

Runnable imageCapture = new Runnable() {

        public void run() {
            // code that takes approximately 270ms
        }
    };

executor = Executors.newScheduledThreadPool(4);
executor.scheduleAtFixedRate(imageCapture, 0, 33, TimeUnit.MILLISECONDS);

Upvotes: 1

Views: 523

Answers (1)

Alexei Kaigorodov
Alexei Kaigorodov

Reputation: 13515

Split the task in two: one makes actual computations and another is executed periodically and starts the first one:

executor = Executors.newScheduledThreadPool(4);

Runnable imageCapture = new Runnable() {

    public void run() {
        // code that takes approximately 270ms
    }
};

Runnable launcher = new Runnable() {

    public void run() {
        executor.execute(imageCapture);
    }
};

executor.scheduleAtFixedRate(launcher, 0, 33, TimeUnit.MILLISECONDS);

Upvotes: 1

Related Questions