astra.execution.BasicSchedulerStrategy Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of astra-interpreter Show documentation
Show all versions of astra-interpreter Show documentation
Core interpreter artifact for the ASTRA Language
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();
}
}