TaskManager.java 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423
  1. /*
  2. * This program is free software: you can redistribute it and/or modify it under
  3. * the terms of the GNU General Public License as published by the Free Software
  4. * Foundation, either version 3 of the License, or (at your option) any later
  5. * version.
  6. *
  7. * This program is distributed in the hope that it will be useful, but WITHOUT
  8. * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
  9. * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
  10. * details.
  11. *
  12. * You should have received a copy of the GNU General Public License along with
  13. * this program. If not, see <http://www.gnu.org/licenses/>.
  14. */
  15. package com.l2jserver.gameserver.taskmanager;
  16. import static com.l2jserver.gameserver.taskmanager.TaskTypes.TYPE_NONE;
  17. import static com.l2jserver.gameserver.taskmanager.TaskTypes.TYPE_SHEDULED;
  18. import static com.l2jserver.gameserver.taskmanager.TaskTypes.TYPE_TIME;
  19. import java.sql.Connection;
  20. import java.sql.PreparedStatement;
  21. import java.sql.ResultSet;
  22. import java.sql.SQLException;
  23. import java.text.DateFormat;
  24. import java.util.Calendar;
  25. import java.util.Date;
  26. import java.util.concurrent.ScheduledFuture;
  27. import java.util.logging.Level;
  28. import java.util.logging.Logger;
  29. import com.l2jserver.L2DatabaseFactory;
  30. import com.l2jserver.gameserver.ThreadPoolManager;
  31. import com.l2jserver.gameserver.taskmanager.tasks.TaskCleanUp;
  32. import com.l2jserver.gameserver.taskmanager.tasks.TaskJython;
  33. import com.l2jserver.gameserver.taskmanager.tasks.TaskOlympiadSave;
  34. import com.l2jserver.gameserver.taskmanager.tasks.TaskRaidPointsReset;
  35. import com.l2jserver.gameserver.taskmanager.tasks.TaskRecom;
  36. import com.l2jserver.gameserver.taskmanager.tasks.TaskRestart;
  37. import com.l2jserver.gameserver.taskmanager.tasks.TaskScript;
  38. import com.l2jserver.gameserver.taskmanager.tasks.TaskSevenSignsUpdate;
  39. import com.l2jserver.gameserver.taskmanager.tasks.TaskShutdown;
  40. import javolution.util.FastList;
  41. import javolution.util.FastMap;
  42. /**
  43. * @author Layane
  44. *
  45. */
  46. public final class TaskManager
  47. {
  48. protected static final Logger _log = Logger.getLogger(TaskManager.class.getName());
  49. protected static final String[] SQL_STATEMENTS = {
  50. "SELECT id,task,type,last_activation,param1,param2,param3 FROM global_tasks",
  51. "UPDATE global_tasks SET last_activation=? WHERE id=?", "SELECT id FROM global_tasks WHERE task=?",
  52. "INSERT INTO global_tasks (task,type,last_activation,param1,param2,param3) VALUES(?,?,?,?,?,?)"
  53. };
  54. private final FastMap<Integer, Task> _tasks = new FastMap<Integer, Task>();
  55. protected final FastList<ExecutedTask> _currentTasks = new FastList<ExecutedTask>();
  56. public class ExecutedTask implements Runnable
  57. {
  58. int id;
  59. long lastActivation;
  60. Task task;
  61. TaskTypes type;
  62. String[] params;
  63. ScheduledFuture<?> scheduled;
  64. public ExecutedTask(Task ptask, TaskTypes ptype, ResultSet rset) throws SQLException
  65. {
  66. task = ptask;
  67. type = ptype;
  68. id = rset.getInt("id");
  69. lastActivation = rset.getLong("last_activation");
  70. params = new String[] { rset.getString("param1"), rset.getString("param2"), rset.getString("param3") };
  71. }
  72. public void run()
  73. {
  74. task.onTimeElapsed(this);
  75. lastActivation = System.currentTimeMillis();
  76. Connection con = null;
  77. try
  78. {
  79. con = L2DatabaseFactory.getInstance().getConnection();
  80. PreparedStatement statement = con.prepareStatement(SQL_STATEMENTS[1]);
  81. statement.setLong(1, lastActivation);
  82. statement.setInt(2, id);
  83. statement.executeUpdate();
  84. statement.close();
  85. }
  86. catch (SQLException e)
  87. {
  88. _log.log(Level.WARNING, "Cannot updated the Global Task " + id + ": " + e.getMessage(), e);
  89. }
  90. finally
  91. {
  92. L2DatabaseFactory.close(con);
  93. }
  94. if (type == TYPE_SHEDULED || type == TYPE_TIME)
  95. {
  96. stopTask();
  97. }
  98. }
  99. @Override
  100. public boolean equals(Object object)
  101. {
  102. return id == ((ExecutedTask) object).id;
  103. }
  104. public Task getTask()
  105. {
  106. return task;
  107. }
  108. public TaskTypes getType()
  109. {
  110. return type;
  111. }
  112. public int getId()
  113. {
  114. return id;
  115. }
  116. public String[] getParams()
  117. {
  118. return params;
  119. }
  120. public long getLastActivation()
  121. {
  122. return lastActivation;
  123. }
  124. public void stopTask()
  125. {
  126. task.onDestroy();
  127. if (scheduled != null)
  128. scheduled.cancel(true);
  129. _currentTasks.remove(this);
  130. }
  131. }
  132. public static TaskManager getInstance()
  133. {
  134. return SingletonHolder._instance;
  135. }
  136. private TaskManager()
  137. {
  138. initializate();
  139. startAllTasks();
  140. }
  141. private void initializate()
  142. {
  143. registerTask(new TaskCleanUp());
  144. registerTask(new TaskScript());
  145. registerTask(new TaskJython());
  146. registerTask(new TaskOlympiadSave());
  147. registerTask(new TaskRaidPointsReset());
  148. registerTask(new TaskRecom());
  149. registerTask(new TaskRestart());
  150. registerTask(new TaskSevenSignsUpdate());
  151. registerTask(new TaskShutdown());
  152. }
  153. public void registerTask(Task task)
  154. {
  155. int key = task.getName().hashCode();
  156. if (!_tasks.containsKey(key))
  157. {
  158. _tasks.put(key, task);
  159. task.initializate();
  160. }
  161. }
  162. private void startAllTasks()
  163. {
  164. Connection con = null;
  165. try
  166. {
  167. con = L2DatabaseFactory.getInstance().getConnection();
  168. PreparedStatement statement = con.prepareStatement(SQL_STATEMENTS[0]);
  169. ResultSet rset = statement.executeQuery();
  170. while (rset.next())
  171. {
  172. Task task = _tasks.get(rset.getString("task").trim().toLowerCase().hashCode());
  173. if (task == null)
  174. continue;
  175. TaskTypes type = TaskTypes.valueOf(rset.getString("type"));
  176. if (type != TYPE_NONE)
  177. {
  178. ExecutedTask current = new ExecutedTask(task, type, rset);
  179. if (launchTask(current))
  180. _currentTasks.add(current);
  181. }
  182. }
  183. rset.close();
  184. statement.close();
  185. }
  186. catch (Exception e)
  187. {
  188. _log.log(Level.SEVERE, "Error while loading Global Task table: " + e.getMessage(), e);
  189. }
  190. finally
  191. {
  192. try
  193. {
  194. L2DatabaseFactory.close(con);
  195. }
  196. catch (Exception e)
  197. {
  198. }
  199. }
  200. }
  201. private boolean launchTask(ExecutedTask task)
  202. {
  203. final ThreadPoolManager scheduler = ThreadPoolManager.getInstance();
  204. final TaskTypes type = task.getType();
  205. long delay, interval;
  206. switch(type)
  207. {
  208. case TYPE_STARTUP:
  209. task.run();
  210. return false;
  211. case TYPE_SHEDULED:
  212. delay = Long.valueOf(task.getParams()[0]);
  213. task.scheduled = scheduler.scheduleGeneral(task, delay);
  214. return true;
  215. case TYPE_FIXED_SHEDULED:
  216. delay = Long.valueOf(task.getParams()[0]);
  217. interval = Long.valueOf(task.getParams()[1]);
  218. task.scheduled = scheduler.scheduleGeneralAtFixedRate(task, delay, interval);
  219. return true;
  220. case TYPE_TIME:
  221. try
  222. {
  223. Date desired = DateFormat.getInstance().parse(task.getParams()[0]);
  224. long diff = desired.getTime() - System.currentTimeMillis();
  225. if (diff >= 0)
  226. {
  227. task.scheduled = scheduler.scheduleGeneral(task, diff);
  228. return true;
  229. }
  230. _log.info("Task " + task.getId() + " is obsoleted.");
  231. }
  232. catch (Exception e)
  233. {
  234. }
  235. break;
  236. case TYPE_SPECIAL:
  237. ScheduledFuture<?> result = task.getTask().launchSpecial(task);
  238. if (result != null)
  239. {
  240. task.scheduled = result;
  241. return true;
  242. }
  243. break;
  244. case TYPE_GLOBAL_TASK:
  245. interval = Long.valueOf(task.getParams()[0]) * 86400000L;
  246. String[] hour = task.getParams()[1].split(":");
  247. if (hour.length != 3)
  248. {
  249. _log.warning("Task " + task.getId() + " has incorrect parameters");
  250. return false;
  251. }
  252. Calendar check = Calendar.getInstance();
  253. check.setTimeInMillis(task.getLastActivation() + interval);
  254. Calendar min = Calendar.getInstance();
  255. try
  256. {
  257. min.set(Calendar.HOUR_OF_DAY, Integer.parseInt(hour[0]));
  258. min.set(Calendar.MINUTE, Integer.parseInt(hour[1]));
  259. min.set(Calendar.SECOND, Integer.parseInt(hour[2]));
  260. }
  261. catch (Exception e)
  262. {
  263. _log.log(Level.WARNING, "Bad parameter on task " + task.getId() + ": " + e.getMessage(), e);
  264. return false;
  265. }
  266. delay = min.getTimeInMillis() - System.currentTimeMillis();
  267. if (check.after(min) || delay < 0)
  268. {
  269. delay += interval;
  270. }
  271. task.scheduled = scheduler.scheduleGeneralAtFixedRate(task, delay, interval);
  272. return true;
  273. default:
  274. return false;
  275. }
  276. return false;
  277. }
  278. public static boolean addUniqueTask(String task, TaskTypes type, String param1, String param2, String param3)
  279. {
  280. return addUniqueTask(task, type, param1, param2, param3, 0);
  281. }
  282. public static boolean addUniqueTask(String task, TaskTypes type, String param1, String param2, String param3, long lastActivation)
  283. {
  284. Connection con = null;
  285. try
  286. {
  287. con = L2DatabaseFactory.getInstance().getConnection();
  288. PreparedStatement statement = con.prepareStatement(SQL_STATEMENTS[2]);
  289. statement.setString(1, task);
  290. ResultSet rset = statement.executeQuery();
  291. if (!rset.next())
  292. {
  293. statement = con.prepareStatement(SQL_STATEMENTS[3]);
  294. statement.setString(1, task);
  295. statement.setString(2, type.toString());
  296. statement.setLong(3, lastActivation);
  297. statement.setString(4, param1);
  298. statement.setString(5, param2);
  299. statement.setString(6, param3);
  300. statement.execute();
  301. }
  302. rset.close();
  303. statement.close();
  304. return true;
  305. }
  306. catch (SQLException e)
  307. {
  308. _log.log(Level.WARNING, "Cannot add the unique task: " + e.getMessage(), e);
  309. }
  310. finally
  311. {
  312. try
  313. {
  314. L2DatabaseFactory.close(con);
  315. }
  316. catch (Exception e)
  317. {
  318. }
  319. }
  320. return false;
  321. }
  322. public static boolean addTask(String task, TaskTypes type, String param1, String param2, String param3)
  323. {
  324. return addTask(task, type, param1, param2, param3, 0);
  325. }
  326. public static boolean addTask(String task, TaskTypes type, String param1, String param2, String param3, long lastActivation)
  327. {
  328. Connection con = null;
  329. try
  330. {
  331. con = L2DatabaseFactory.getInstance().getConnection();
  332. PreparedStatement statement = con.prepareStatement(SQL_STATEMENTS[3]);
  333. statement.setString(1, task);
  334. statement.setString(2, type.toString());
  335. statement.setLong(3, lastActivation);
  336. statement.setString(4, param1);
  337. statement.setString(5, param2);
  338. statement.setString(6, param3);
  339. statement.execute();
  340. statement.close();
  341. return true;
  342. }
  343. catch (SQLException e)
  344. {
  345. _log.log(Level.WARNING, "Cannot add the task: " + e.getMessage(), e);
  346. }
  347. finally
  348. {
  349. try
  350. {
  351. L2DatabaseFactory.close(con);
  352. }
  353. catch (Exception e)
  354. {
  355. }
  356. }
  357. return false;
  358. }
  359. @SuppressWarnings("synthetic-access")
  360. private static class SingletonHolder
  361. {
  362. protected static final TaskManager _instance = new TaskManager();
  363. }
  364. }