1. 程式人生 > >java定時器處理超時未支付訂單

java定時器處理超時未支付訂單

1、核心程式碼
public class MyTimerTask implements ServletContextListener {

	private Timer timer = null;

	// 初始化監聽器,建立例項,執行任務

	public void contextInitialized(ServletContextEvent event) {
		timer = new Timer();
		Timer timer = new Timer();
		timer.schedule(new TimerTask() {
			public void run() {
				Connection conn = null;
				ResultSet rs = null;
				PreparedStatement st = null;
				try {
					conn = DbUtil.getConnection();
					conn.setAutoCommit(false);
					java.util.Date date = new Date();
					System.out.println("開始查詢超時未支付訂單...");
					rs = DbUtil.getResultSet(conn,
							"select id, last_payment from mat_info where pay_status=0 and last_payment <'"+ date + "'");
					while (rs.next()) {
						System.out.println("timeout order id is"+ rs.getString("id"));
						st = conn.prepareStatement("update mat_info set room_id ='' where pay_status=0 and id='"+ rs.getString("id") + "'");
						st.execute();
					}
					conn.commit();
				} catch (Exception e) {
					System.out.println(e);
					try {
						conn.rollback();
					} catch (SQLException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
					e.printStackTrace();
				} finally {
					DbUtil.closeResultSet(rs);
					DbUtil.closeConnection(conn);
				}
			}
		}, 1000, 15000);
	}

	// 銷燬監聽器,停止執行任務

	public void contextDestroyed(ServletContextEvent event) {
		// 確保正在執行的任務是此計時器所執行的最後一個任務。
		timer.cancel();
	}

}

2、配置

在web.xml裡面新增如下配置

<listener>     
          <listener-class>     
	       com.lcychina.utils.MyTimerTask     
	  </listener-class>     
</listener>