package org.ut.cmldep;

import org.ut.cmldep.experiments.Experiment;
import org.ut.cmldep.experiments.ExperimentLogger;

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

import static java.util.concurrent.TimeUnit.SECONDS;

/**
 * Created by Iurii on 4/22/2015.
 */
public class ExperimentExecutor {

    private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);

    public ExperimentExecutor(){
    }

    public void start(int timeOfExperiment, int delay, String fileName){

        System.out.println("============== Start Executor service ======================");
        final ScheduledFuture<?>[] executeHandles = new ScheduledFuture<?>[2];

        executeHandles[0] = scheduler.scheduleAtFixedRate(new Experiment(), delay, delay, SECONDS);
        executeHandles[1] = scheduler.scheduleAtFixedRate(new ExperimentLogger(fileName), delay, delay, SECONDS);

        scheduler.schedule(new Runnable() {
            public void run() {
                for (ScheduledFuture sf : executeHandles) {
                    sf.cancel(true);
                }

                System.out.println("============== Stop Executor service ======================");
            }
        }, timeOfExperiment, SECONDS);
    }
}
