TaskManager.java 11 KB

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