All Downloads are FREE. Search and download functionalities are using the official Maven repository.

astra.execution.BasicSchedulerStrategy Maven / Gradle / Ivy

There is a newer version: 1.4.2
Show newest version
package astra.execution;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import astra.core.Agent;
import astra.core.Scheduler;
import astra.core.Task;

public class BasicSchedulerStrategy implements SchedulerStrategy {
	private ExecutorService executor = Executors.newFixedThreadPool(2);
	private Map agents = new HashMap();
	private long sleepTime = 50;
	
	public void schedule(final Agent agent) {
		Integer state = agents.get(agent.name());
		if (state == null) {
			agents.put(agent.name(), state = Scheduler.ACTIVE);
		}
		
		if (state == Scheduler.ACTIVE) {
			executor.submit(new Runnable() {
				public void run() {
					try {
						agent.execute();
					} catch (Throwable th) {
						System.err.println("Major Error in Agent: " + agent.name());
						th.printStackTrace();
						System.exit(0);
					}
					
					try {
						Thread.sleep(sleepTime);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					
					Scheduler.schedule(agent);
				}
			});
		}
	}

	public void schedule(Task task) {
		executor.submit(task);
	}

	public void setThreadPoolSize(int size) {
		ExecutorService oldExecutor = executor;
		executor = Executors.newFixedThreadPool(size);
		oldExecutor.shutdown();
	}

	public void stop() {
	}

	public void setState(Agent agent, int state) {
		agents.put(agent.name(), state);
		
	}

	public int getState(Agent agent) {
		return agents.get(agent.name());
	}

	public void setSleepTime(long sleepTime) {
		this.sleepTime=sleepTime;
	}

	@Override
	public void shutdown() {
		executor.shutdown();

	}

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy