设置全局的timer需要在web.xml中添加servlet, 并设置load-on-startup 为 1, 然后在servlet的init()中开启timer, 具体代码如下:
1. web.xml
<servlet> <servlet-name>backup</servlet-name> <servlet-class>locationService.backup.Backup</servlet-class> <load-on-startup>1</load-on-startup> </servlet>
2. Backup.java
public class Backup extends HttpServlet { private static final long serialVersionUID = 1L; private static final Logger logger = Logger.getLogger(Backup.class); public void init() throws ServletException { TimerTask bakcupTask = new TimerTask(){ public void run(){ try { backup(); } catch (Exception e) { e.printStackTrace(); } } }; /* Schedule the task to be run every 24 hours */ Timer time = new Timer(); time.scheduleAtFixedRate(bakcupTask, new Date(),1000*60*60*24); } ...
时间: 2024-10-19 21:57:37