Ben Lawton
Ben Lawton

Reputation: 159

Java: execute Runnable fixed number of times

So I have a piece of code that I want to execute repeatedly. I get this part. The problem is that I want to execute the code at fixed intervals, but only a fixed number (in this case 1440) times.

Any ideas how I'd do that?

Here's the code:

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;


public class Simulator {

    public static int TICK = 10;
    public static int NUM_OF_SERVERS = 3;
    public static int LENGTH_OF_SIMULATION = 1440;

    public static void main(String[] args) {


        final MultiQueueControlSystem multiController = MultiQueueControlSystem.getInstance();
        final SingleQueueControlSystem singleController = SingleQueueControlSystem.getInstance();

        multiController.generateQueuesAndServers(NUM_OF_SERVERS);
        singleController.generateQueuesAndServers(NUM_OF_SERVERS);

        final ScheduledExecutorService ticker = Executors.newSingleThreadScheduledExecutor();

        ticker.scheduleAtFixedRate(new Runnable() {

            int currentTime = 0;

            public void run() {

                if(currentTime < LENGTH_OF_SIMULATION) {
                    currentTime = currentTime + 1;
                } else {
                    ticker.shutdown();
                    return;
                }

                multiController.customerArrival();
                multiController.allocateCustomersToServers();
                multiController.removeFinishedCustomersFromServers();

                singleController.customerArrival();
                singleController.allocateCustomersToServers();
                singleController.removeFinishedCustomersFromServers();
            }
        }, 1, TICK, TimeUnit.MILLISECONDS);
    }
}

Upvotes: 3

Views: 2672

Answers (2)

gursahib.singh.sahni
gursahib.singh.sahni

Reputation: 1597

try this

Take any integer variable runCount (increment after every cycle) and service the object returned from scheduleAtFixedRate method

if(runCount == LENGTH_OF_SIMULATION ) { service.cancel(false); }

Upvotes: 0

Brett Okken
Brett Okken

Reputation: 6306

Consider giving your runnable a reference to the ScheduledExecutorService. Then instead of scheduling at a fixed rate, just schedule for future execution. Have the runnable instance keep tracker (through an AtomicInteger) how many times it has been executed. When it completes it's normal execution it can schedule itself for future execution. Once it has executed the desired number of times, it would not schedule itself again.

Upvotes: 2

Related Questions