Servlet中执行定时任务

由于用spring配置的quartz在启动后不能获得UOWManager,考虑多时,只好在servlet启动时候执行定时任务。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
import java.io.IOException;
import java.util.Timer;

import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.persistence.EntityManager;
import javax.persistence.Persistence;
import javax.servlet.GenericServlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import org.apache.log4j.Logger;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.ibm.websphere.uow.UOWSynchronizationRegistry;
import com.ibm.ws.uow.UOWManager;
import com.ibm.wsspi.uow.UOWAction;
import com.ibm.wsspi.uow.UOWActionException;
import com.ibm.wsspi.uow.UOWException;

public class CronJobServlet extends GenericServlet {
private static final Logger log = Logger.getLogger(CronJobServlet.class);
private static UOWManager manager;
private static EntityManager em;
private XXJob clearXXJob;

@Override
public void init(ServletConfig config) throws ServletException {
initJob(config);
try {
InitialContext ic = new InitialContext();
manager = (UOWManager) ic.lookup("java:comp/websphere/UOWManager");
} catch (NamingException e) {
e.printStackTrace();
}
try {
manager.runUnderUOW(
UOWSynchronizationRegistry.UOW_TYPE_GLOBAL_TRANSACTION,
false, new UOWAction() {
public void run() throws Exception {
Timer timer = new Timer();
timer.schedule(clearXXJob, 2000,1000);
}

});
} catch (UOWActionException e) {
e.printStackTrace();
} catch (UOWException e) {
e.printStackTrace();
}

}

private void initJob(ServletConfig config) {
em = Persistence.createEntityManagerFactory("xx")
.createEntityManager();

final CronJobService cronJobService = (CronJobService) WebApplicationContextUtils
.getWebApplicationContext(config.getServletContext()).getBean(
"cronJobService");
cronJobService.setEntityManager(em);
clearXXJob = new ClearXXJob(cronJobService);
}

@Override
public void service(ServletRequest arg0, ServletResponse arg1)
throws ServletException, IOException {

}
}