TaskManager.java 11 KB

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