Batch Schedule

Run
How to run the sample
The source code for this sample can be found in the javaee7-samples GitHub repository. The first thing we need to do is to get the source by downloading the repository and then go into the samples folder:
git clone git://github.com/javaee-samples/javaee7-samples.git
cd javaee7-samples/batch/scheduling/
Now we are ready to start testing. You can run all the tests in this sample by executing:
mvn test
Or you can run individual tests by executing one of the following:
mvn test -Dtest=ManagedScheduledBatchTestmvn test -Dtest=TimerScheduleBatchTest

Scheduling a Batch Job

ManagedScheduledBatchTest

The Batch specification does not offer anything to schedule jobs. However, the Java EE plataform offer a few ways that allow you to schedule Batch jobs.

Adding a Trigger to a ManagedScheduledExecutorService is possible to trigger an execution of the batch job by specifying the next execution date of the job.

@Stateless()
@Local(MyManagedScheduledBatch.class)
public class MyManagedScheduledBatchBean implements MyManagedScheduledBatch {

    public MyManagedScheduledBatchBean();
    @Resource()
    private ManagedScheduledExecutorService executor;

    @Override()
    public void runJob();

    public void runJob2();

    protected MyJob createJob();
}

We’re just going to deploy the application as a web archive. Note the inclusion of the following files:

/META-INF/batch-jobs/myJob.xml

The myJob.xml file is needed for running the batch definition. We are also adding an alternative bean to override the created batch instance do we can track it’s status and the modified batch instance.

Warning
MyJobAlternative not found
Warning
MyManagedScheduledBatchAlternative not found
@Deployment
public static WebArchive createDeployment() {
    BeansDescriptor beansXml = Descriptors.create(BeansDescriptor.class);

    WebArchive war = ShrinkWrap.create(WebArchive.class)
            .addClasses(
                    MyBatchlet.class,
                    MyJob.class,
                    MyJobAlternative.class,
                    MyManagedScheduledBatch.class,
                    MyManagedScheduledBatchBean.class,
                    MyManagedScheduledBatchAlternative.class)
            .addAsWebInfResource(
                    new StringAsset(beansXml.createAlternatives().clazz(
                            MyManagedScheduledBatchAlternative.class.getName()).up().exportAsString()),
                    beansXml.getDescriptorName())
            .addAsResource("META-INF/batch-jobs/myJob.xml");
    System.out.println(war.toString(true));
    return war;
}

The batch job is scheduled to execute each 15 seconds. We expect to run the batch instance exactly 3 times as defined in the CountDownLatch object. To validate the test expected behaviour we just need to check the Batch Status in the JobExecution object. We should get a COMPLETED for every execution.

@Test
public void testTimeScheduleBatch() throws Exception {
    managedScheduledBatch.runJob();

    MyJobAlternative.managedScheduledCountDownLatch.await(90, TimeUnit.SECONDS);

    assertEquals(0, MyJobAlternative.managedScheduledCountDownLatch.getCount());
    assertEquals(3, MyJob.executedBatchs.size());

    for (Long executedBatch : MyJob.executedBatchs) {
        assertEquals(BatchStatus.COMPLETED,
                BatchRuntime.getJobOperator().getJobExecution(executedBatch).getBatchStatus());
    }
}

TimerScheduleBatchTest

The Batch specification does not offer anything to schedule jobs. However, the Java EE plataform offer a few ways that allow you to schedule Batch jobs.

Annotating a method bean with Schedule, it’s possible to schedule an execution of a batch job by the specified cron expression in the Schedule annotation.

Warning
AbstractTimerBatch not found
@Startup()
@Singleton()
public class MyTimerScheduleBean extends AbstractTimerBatch {

    public MyTimerScheduleBean();
}

We’re just going to deploy the application as a web archive. Note the inclusion of the following files:

/META-INF/batch-jobs/myJob.xml

The myJob.xml file is needed for running the batch definition. We are also adding an alternative bean to override the batch schedule timeout and track the execution calls,

Warning
MyTimerScheduleAlternative not found
@Deployment
public static WebArchive createDeployment() {
    WebArchive war = ShrinkWrap.create(WebArchive.class)
            .addClasses(
                    MyBatchlet.class,
                    MyJob.class,
                    AbstractTimerBatch.class,
                    MyTimerScheduleAlternative.class)
            .addAsWebInfResource(EmptyAsset.INSTANCE, ArchivePaths.create("beans.xml"))
            .addAsResource("META-INF/batch-jobs/myJob.xml");

    System.out.println(war.toString(true));
    return war;
}

The batch job is scheduled to execute each 15 seconds. We expect to run the batch instance exactly 3 times as defined in the CountDownLatch object. To validate the test expected behaviour we just need to check the Batch Status in the JobExecution object. We should get a COMPLETED for every execution.

@Test
public void testTimeScheduleBatch() throws Exception {
    MyTimerScheduleAlternative.timerScheduleCountDownLatch.await(90, TimeUnit.SECONDS);

    assertEquals(0, MyTimerScheduleAlternative.timerScheduleCountDownLatch.getCount());
    assertEquals(3, MyTimerScheduleAlternative.executedBatchs.size());

    for (Long executedBatch : MyTimerScheduleAlternative.executedBatchs) {
        assertEquals(BatchStatus.COMPLETED,
                BatchRuntime.getJobOperator().getJobExecution(executedBatch).getBatchStatus());
    }
}

Share the Knowledge

Find this sample useful? Share on

There's a lot more about JavaEE to cover. If you're ready to learn more, check out the other available samples.

Help Improve

Find a bug in the sample? Something missing? You can fix it by editing the source, making the correction and sending a pull request. Or report the problem to the issue tracker

Recent Changelog

  • Jul 09, 2014: Added tests to scheduling project by Roberto Cortez
  • Jul 08, 2014: Adding a new sample to schedule batch jobs by arun-gupta
How to help improve this sample
The source code for this sample can be found in the javaee7-samples GitHub repository. The first thing you need to do is to get the source by downloading the repository and then go into the samples folder:
git clone git://github.com/javaee-samples/javaee7-samples.git
cd javaee7-samples/batch/scheduling/

Do the changes as you see fit and send a pull request!

Good Luck!