Recurring task in java

1.5k views Asked by At

I have a runnable object that is being updated every run (class variables). I want to be able to execute it in a single thread (presumeably SingleThreadExecutor?) BUT only after the previous run has completed.

I have tried Executors.newSingleThreadScheduledExecutor() but it only offers time-based recurring tasks.

Also another problem I encountered that if I schedule the same runnable over and over (in a loop) it runs only once.

How can I acheive what I want?

The class:

public class Population implements Runnable{
 private int count=0;
 ...

@Override
public void run(){
    evaluateAll();

    List<Individual> parents = elitism();

    individuals.clear();

    for (int i = 0; i < popSize; i++) {
        Individual child = Individual.uniformCrossover(parents);
        if(Utilities.RANDOM.nextDouble() < mrate)
            child.mutate();
        individuals.add(child);
    }

    System.out.println(this);
 }
}

The launching part:

Population population = new Population();
    ScheduledExecutorService ses = Executors
            .newSingleThreadScheduledExecutor();
    for (int i = 0; i < 300; i++)
        ses.schedule(population, 0, TimeUnit.MILLISECONDS);
    ses.shutdown();
1

There are 1 answers

3
Sotirios Delimanolis On BEST ANSWER

You can simply run your code in a loop in a dedicated thread

public static void main(String[] args) throws Exception {
    ExecutorService executorService = Executors.newSingleThreadExecutor();
    executorService.submit(() -> {
        for (;;)
            statefulRunnable.run();
    });
}

public static final Runnable statefulRunnable = new Runnable() {
    private int state;

    @Override
    public void run() {
        state++;
    }
};