2 * Rhynodge - Engine.java - Copyright © 2013 David Roden
4 * This program is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
18 package net.pterodactylus.rhynodge.engine;
20 import static java.lang.System.currentTimeMillis;
21 import static java.util.concurrent.TimeUnit.MILLISECONDS;
24 import java.util.Optional;
25 import java.util.concurrent.ConcurrentHashMap;
26 import java.util.concurrent.Future;
27 import java.util.concurrent.ScheduledExecutorService;
28 import java.util.concurrent.ScheduledFuture;
29 import java.util.concurrent.ScheduledThreadPoolExecutor;
31 import javax.inject.Inject;
32 import javax.inject.Singleton;
34 import net.pterodactylus.rhynodge.Reaction;
35 import net.pterodactylus.rhynodge.actions.EmailAction;
36 import net.pterodactylus.rhynodge.states.StateManager;
39 * Rhynodge main engine.
41 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
46 private final StateManager stateManager;
47 private final ScheduledExecutorService executorService;
48 private final Map<String, Future<?>> scheduledFutures = new ConcurrentHashMap<>();
49 private final EmailAction errorEmailAction;
52 public Engine(StateManager stateManager, EmailAction errorEmailAction) {
53 this.stateManager = stateManager;
54 this.errorEmailAction = errorEmailAction;
55 executorService = new ScheduledThreadPoolExecutor(1);
63 * Adds the given reaction to this engine.
66 * The name of the reaction
68 * The reaction to add to this engine
70 public void addReaction(String name, Reaction reaction) {
71 ReactionState reactionState = new ReactionState(stateManager, name);
72 Optional<net.pterodactylus.rhynodge.State> lastState = reactionState.loadLastState();
73 long lastExecutionTime = lastState.map(net.pterodactylus.rhynodge.State::time).orElse(0L);
74 long nextExecutionTime = lastExecutionTime + reaction.updateInterval();
75 ReactionRunner reactionRunner = new ReactionRunner(reaction, reactionState, errorEmailAction);
76 ScheduledFuture<?> future = executorService.scheduleWithFixedDelay(reactionRunner, nextExecutionTime - currentTimeMillis(), reaction.updateInterval(), MILLISECONDS);
77 scheduledFutures.put(name, future);
81 * Removes the reaction with the given name.
84 * The name of the reaction to remove
86 public void removeReaction(String name) {
87 if (!scheduledFutures.containsKey(name)) {
90 scheduledFutures.remove(name).cancel(true);