1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.kuali.hr.time.batch;
17
18 import org.apache.commons.lang.StringUtils;
19 import org.apache.log4j.Logger;
20 import org.kuali.hr.time.service.base.TkServiceLocator;
21 import org.kuali.hr.time.util.TkConstants;
22 import org.springframework.transaction.TransactionStatus;
23 import org.springframework.transaction.support.TransactionCallbackWithoutResult;
24
25 public abstract class BatchJobEntryRunnable implements Runnable{
26
27 private Logger LOG = Logger.getLogger(BatchJobEntryRunnable.class);
28
29 long startTime;
30 long endTime;
31 Long tkBatchJobEntryId;
32 Long tkBatchJobId;
33 BatchJobEntry batchJobEntry;
34
35 public BatchJobEntryRunnable(BatchJobEntry entry) {
36 this.batchJobEntry = entry;
37 this.tkBatchJobEntryId = entry.getTkBatchJobEntryId();
38 this.tkBatchJobId = entry.getTkBatchJobId();
39 }
40
41
42
43
44
45 void doBeforeRun() {
46 startTime = System.currentTimeMillis();
47 LOG.debug("Before run.");
48 batchJobEntry.setBatchJobEntryStatus(TkConstants.BATCH_JOB_ENTRY_STATUS.RUNNING);
49 TkServiceLocator.getBatchJobEntryService().saveBatchJobEntry(batchJobEntry);
50 }
51
52 @Override
53 public final void run() {
54 TkServiceLocator.getTransactionTemplate().execute(new TransactionCallbackWithoutResult() {
55 @Override
56 protected void doInTransactionWithoutResult(TransactionStatus status) {
57 try {
58 doBeforeRun();
59 doWork();
60 doAfterRun();
61 } catch (Throwable t) {
62 LOG.warn("BatchJobEntry: " + batchJobEntry.getTkBatchJobEntryId() + " in Exception status.");
63 batchJobEntry.setBatchJobException(t.getStackTrace().toString());
64 }
65 };
66 });
67 }
68
69
70
71
72
73
74
75
76 public abstract void doWork() throws Exception;
77
78
79
80
81
82 void doAfterRun() {
83 endTime = System.currentTimeMillis();
84 long runtime = endTime - startTime;
85 runtime = (runtime > 0) ? runtime : 1;
86 LOG.debug("Job finished in " + runtime / 1000 + " seconds.");
87
88 if (StringUtils.isEmpty(batchJobEntry.getBatchJobException())) {
89 batchJobEntry.setBatchJobEntryStatus(TkConstants.BATCH_JOB_ENTRY_STATUS.FINISHED);
90 } else {
91 batchJobEntry.setBatchJobEntryStatus(TkConstants.BATCH_JOB_ENTRY_STATUS.EXCEPTION);
92 }
93 TkServiceLocator.getBatchJobEntryService().saveBatchJobEntry(batchJobEntry);
94 }
95
96 public Long getTkBatchJobEntryId() {
97 return tkBatchJobEntryId;
98 }
99
100 public Long getTkBatchJobId() {
101 return tkBatchJobId;
102 }
103
104 public BatchJobEntry getBatchJobEntry() {
105 return batchJobEntry;
106 }
107 }