TaskManager.java 11 KB

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