1,先开发一下定时器 public class JobSqlTimer extends Timer { private static JobSqlTimer jpt = new JobSqlTimer(); public static void start() { Date date = new Date(); date.setHours(0); date.setMinutes(10); date.setSeconds(0); jpt.scheduleAtFixedRate(new JobSqlTimerTask(), date, 30 * 24 * 60 * 60 * 1000); System.out.println("New JobPlanTimer already started...."); } public static void stop() { } public static void main(String[] args) { start(); } } 2,再写一下定时任务 public class JobSqlTimerTask extends TimerTask { private static Logger logger = Logger.getLogger(JobSqlTimerTask.class); public void run() { logger.debug("清理超时扫描表任务开始......"); SqlTaskRun r = new SqlTaskRun(); r.clearDB(); logger.debug("清理超时扫描表任务结束"); } } 3,写一个自己要执行的任务,以便定时调用 public class SqlTaskRun { private static Logger logger = Logger.getLogger(SqlTaskRun.class); public void clearDB() { Connection con = null; Statement stmt = null; String sql1 = "delete tbl_nsp_schedule s where s.workitemid in(" + "select w.workitemindex from wf_tbl_workitem_nsp w where w.workitemstate=1)"; String sql2 = "delete tbl_nsp_schedule s where s.processid in(" + "select d.draftid from tbl_process_draft d where d.endtime is not null)"; try { con = getConnection(); stmt = con.createStatement(); stmt.execute(sql1); stmt.execute(sql2); } catch (SQLException ex) { logger.error(ex); throw new RuntimeException(ex); } finally { closeConnection(con); } } public static Connection getConnection() { try { return DBHelper.getConnection(); } catch (Exception e) { logger.error(e); throw new RuntimeException(e); } } public static void closeConnection(Connection con) { try { if (con != null) { con.close(); } } catch (Exception ex) { } } } 4,编写一下servlet的启动类 public class JobSqlTimerServelt extends HttpServlet { public void init() throws ServletException { System.out.println("initial Sql timer ..."); JobSqlTimer.start(); System.out.println("Sql Timer started ..."); } public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { JobSqlTimer.start(); } public void destroy() { JobSqlTimer.stop(); } } 5,在web.xml文件中进行配置启动 <servlet> <servlet-name>JobSqlTimerServelt</servlet-name> <servlet-class>cn.com.xinli.common.task.JobSqlTimerServelt</servlet-class> <load-on-startup>1</load-on-startup> </servlet> 6,然后启动服务后,以后这个就任务就会按时运行了。