TaskManager.java 11 KB

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