TaskManager.java 11 KB

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