|
| 1 | +package org.javaee7.batch.samples.scheduling; |
| 2 | + |
| 3 | +import javax.annotation.Resource; |
| 4 | +import javax.batch.runtime.BatchRuntime; |
| 5 | +import javax.batch.runtime.BatchStatus; |
| 6 | +import javax.ejb.Local; |
| 7 | +import javax.ejb.Stateless; |
| 8 | +import javax.enterprise.concurrent.LastExecution; |
| 9 | +import javax.enterprise.concurrent.ManagedScheduledExecutorService; |
| 10 | +import javax.enterprise.concurrent.Trigger; |
| 11 | +import java.util.Calendar; |
| 12 | +import java.util.Date; |
| 13 | +import java.util.List; |
| 14 | +import java.util.concurrent.TimeUnit; |
| 15 | + |
| 16 | +/** |
| 17 | + * @author arungupta |
| 18 | + */ |
| 19 | +@Stateless |
| 20 | +@Local(MyManagedScheduledBatch.class) |
| 21 | +public class MyManagedScheduledBatchBean implements MyManagedScheduledBatch { |
| 22 | + @Resource |
| 23 | + private ManagedScheduledExecutorService executor; |
| 24 | + |
| 25 | + @Override |
| 26 | + public void runJob() { |
| 27 | + executor.schedule(createJob(), new Trigger() { |
| 28 | + |
| 29 | + @Override |
| 30 | + public Date getNextRunTime(LastExecution lastExecutionInfo, Date taskScheduledTime) { |
| 31 | + if (MyJob.executedBatchs.size() >= 3) { |
| 32 | + return null; |
| 33 | + } |
| 34 | + |
| 35 | + Calendar cal = Calendar.getInstance(); |
| 36 | + |
| 37 | + if (lastExecutionInfo == null) { |
| 38 | + cal.setTime(taskScheduledTime); |
| 39 | + } else { |
| 40 | + cal.setTime(lastExecutionInfo.getRunStart()); |
| 41 | + } |
| 42 | + |
| 43 | + cal.add(Calendar.SECOND, 10); |
| 44 | + return cal.getTime(); |
| 45 | + } |
| 46 | + |
| 47 | + @Override |
| 48 | + public boolean skipRun(LastExecution lastExecutionInfo, Date scheduledRunTime) { |
| 49 | + List<Long> executedBatchs = MyJob.executedBatchs; |
| 50 | + |
| 51 | + for (Long executedBatch : executedBatchs) { |
| 52 | + if (!BatchRuntime.getJobOperator().getJobExecution(executedBatch).getBatchStatus().equals( |
| 53 | + BatchStatus.COMPLETED)) { |
| 54 | + return true; |
| 55 | + } |
| 56 | + } |
| 57 | + |
| 58 | + return false; |
| 59 | + } |
| 60 | + |
| 61 | + }); |
| 62 | + } |
| 63 | + |
| 64 | + public void runJob2() { |
| 65 | + executor.scheduleWithFixedDelay(new MyJob(), 1, 2, TimeUnit.MINUTES); |
| 66 | + } |
| 67 | + |
| 68 | + protected MyJob createJob() { |
| 69 | + return new MyJob(); |
| 70 | + } |
| 71 | +} |
0 commit comments