Scheduler

EJB3.1 Automatic Schedulers in JBoss AS7

Hi,

Job Scheduling is one of the most important in while working in admin profile or for the developers. There were various options available for job scheduling, but as this has become a most findamental requirement for most of the applications or admins, So now as part of EE6 we can crate our own Automatic Schedulers/timers using the annotation “javax.ejb.Schedule”.

Enterprise bean timers are either programmatic timers or automatic timers. In this example we will see how we can create an “Automatic Timer”, Timers can be set according to a calendar-based schedule and these are very easy to maintain. Schedule a timer for automatic creation with a timeout schedule based on a cron-like time expression. The annotated method is used as the timeout callback method. All elements of this annotation are optional. If none are specified a persistent timer will be created with callbacks occuring every day at midnight in the default time zone associated with the container in which the application is executing. For more information on this you can refer to the following link:
http://docs.oracle.com/javaee/6/api/javax/ejb/Schedule.html

Step1). Create a Directory somewhere inside your file system where we can create our web application. Suppose i am creating a directory as “/home/userone/EJB31_Automatic_Scheduler” and the create a subdirectory with name “src” inside “/home/userone/EJB31_Automatic_Scheduler”

Step2). Now we will write the Scheduler Bean “AutomaticSchedulerBean.java” program inside the “/home/userone/EJB31_Automatic_Scheduler/src” directory which will have a method “backgroundProcessing()” and it will run on scheduled time as mentioned below:

dayOfWeek=* means all the seven days of a week
hour = “*” means every hour of a day
minute = “*” means every minute
second=”*/5″ means every five second interval
year=”2012″ means in the year 2012

package test;
import javax.ejb.Stateless;
import java.util.Date;
import javax.ejb.Schedule;

@Stateless(name="AutomaticSchedulerBean")
public class AutomaticSchedulerBean
 {
     @Schedule(dayOfWeek = "*", hour = "*", minute = "*", second = "*/5",year="2012", persistent = false)
     public void backgroundProcessing()
	    {
		   System.out.println("\n\n\t AutomaticSchedulerBean's backgroundProcessing() called....at: "+new Date());
	    }
 }

Step3). Now we will write a simple ant “build.xml” file in order to build the scheduler JAR and deploy it on JBoss AS7. So write the following “build.xml” file inside “/home/userone/EJB31_Automatic_Scheduler” as following:

<project name="Secured EJB Remote" default="all">
<property name="jboss.home" value="/home/userone/jboss-as-7.1.0.CR1b" />
<property name="jboss.module.dir" value="${jboss.home}/modules" />
<property name="basedir" value="." />
<property name="tmp.dir" value="tmp" />
<property name="src.dir" value="src" />
<property name="output.dir" value="build" />
<property name="ejb.jar" value="schedulerEJB.jar" />

        <path id="jboss.classpath">
           <fileset dir="${jboss.module.dir}">
               <include name="**/*.jar"/>
           </fileset>
        </path>

        <target name="all" depends="deploy" />

        <target name="build_ejb_jar">
           <delete dir="${output.dir}" />
           <delete dir="${tmp.dir}" />
           <mkdir dir="${output.dir}" />
           <mkdir dir="${tmp.dir}" />
           <javac srcdir="${src.dir}" destdir="${tmp.dir}"  includes="*.java" classpathref="jboss.classpath"/> 

           <jar jarfile="${tmp.dir}/${ejb.jar}" basedir="${tmp.dir}" compress="true" />
           <copy file="${tmp.dir}/${ejb.jar}" tofile="${output.dir}/${ejb.jar}"/>

           <delete dir="${tmp.dir}"/>
        </target>

        <target name="deploy" depends="build_ejb_jar">
            <echo message="*******************  Deploying the EAR file ${ear.name} *********************" />
            <echo message="********** ${output.dir}/${ejb.jar} to ${jboss.home}/standalone/deployments **********" />
            <copy todir="${jboss.home}/standalone/deployments/">
                <fileset dir="${output.dir}/">
                  <include name="${ejb.jar}"/>
                </fileset>
            </copy>
            <echo message="*******************  Deployed Successfully   *********************" />
            <echo message="******************* Check JBoss AS7 Console  *********************" />
        </target>

</project>

NOTE: The only change in the above file you need to do is to change the “jboss.home” directory path in the second line of the above script is to point to your own JBoss AS7 directory home directory.

Step4). Now before running your ANT script to build and deploy the above webapplication you should have the ANT as well as JAVA set in the $PATH variable of the Shell / command prompt as following:

For Unix Based OS:
export PATH=/home/userone/jdk1.6.0_21/bin:/home/userone/apache-ant-1.8.2/bin:$PATH

For Windows Based OS:
set PATH=C:/jdk1.6.0_21/bin;C:/apache-ant-1.8.2/bin;%PATH%

Step5). Now run the ant file from the directory where you have placed the “build.xml” file as following:

[userone@localhost EJB31_Automatic_Scheduler]$ ant
Buildfile: build.xml

build_ejb_jar:
   [delete] Deleting directory /home/userone/EJB31_Automatic_Scheduler/build
    [mkdir] Created dir: /home/userone/EJB31_Automatic_Scheduler/build
    [mkdir] Created dir: /home/userone/EJB31_Automatic_Scheduler/tmp
    [javac] Compiling 1 source file to /home/userone/EJB31_Automatic_Scheduler/tmp
      [jar] Building jar: /home/userone/EJB31_Automatic_Scheduler/tmp/schedulerEJB.jar
     [copy] Copying 1 file to /home/userone/EJB31_Automatic_Scheduler/build
   [delete] Deleting directory /home/userone/EJB31_Automatic_Scheduler/tmp

deploy:
     [echo] *******************  Deploying the EAR file ${ear.name} *********************
     [echo] ********** build/schedulerEJB.jar to /home/userone/jboss-as-7.1.0.CR1b/standalone/deployments **********
     [copy] Copying 1 file to /home/userone/jboss-as-7.1.0.CR1b/standalone/deployments
     [echo] *******************  Deployed Successfully   *********************
     [echo] ******************* Check JBoss AS7 Console  *********************

all:

BUILD SUCCESSFUL
Total time: 4 seconds

Step6). Now as soon the above Scheduler is deployed on the JBoss AS7 we will see this kind of messages in the JBoss AS7 Console.

15:14:33,655 INFO  [org.jboss.as.server.deployment] (MSC service thread 1-7) Starting deployment of "schedulerEJB.jar"
15:14:34,085 INFO  [org.jboss.as.ejb3.deployment.processors.EjbJndiBindingsDeploymentUnitProcessor] (MSC service thread 1-5) JNDI bindings for session bean named AutomaticSchedulerBean in deployment unit deployment "schedulerEJB.jar" are as follows:

	java:global/schedulerEJB/AutomaticSchedulerBean!test.AutomaticSchedulerBean
	java:app/schedulerEJB/AutomaticSchedulerBean!test.AutomaticSchedulerBean
	java:module/AutomaticSchedulerBean!test.AutomaticSchedulerBean
	java:global/schedulerEJB/AutomaticSchedulerBean
	java:app/schedulerEJB/AutomaticSchedulerBean
	java:module/AutomaticSchedulerBean

15:14:34,477 INFO  [org.jboss.as.server] (DeploymentScanner-threads - 2) JBAS018559: Deployed "schedulerEJB.jar"
15:14:35,014 INFO  [stdout] (pool-9-thread-1)
15:14:35,015 INFO  [stdout] (pool-9-thread-1)
15:14:35,015 INFO  [stdout] (pool-9-thread-1) 	 AutomaticSchedulerBean's backgroundProcessing() called....at: Sun Jan 29 15:14:35 IST 2012
15:14:40,015 INFO  [stdout] (pool-9-thread-2)
15:14:40,015 INFO  [stdout] (pool-9-thread-2)
15:14:40,015 INFO  [stdout] (pool-9-thread-2) 	 AutomaticSchedulerBean's backgroundProcessing() called....at: Sun Jan 29 15:14:40 IST 2012
15:14:45,003 INFO  [stdout] (pool-9-thread-3)
15:14:45,003 INFO  [stdout] (pool-9-thread-3)
15:14:45,003 INFO  [stdout] (pool-9-thread-3) 	 AutomaticSchedulerBean's backgroundProcessing() called....at: Sun Jan 29 15:14:45 IST 2012
15:14:50,003 INFO  [stdout] (pool-9-thread-4)
15:14:50,003 INFO  [stdout] (pool-9-thread-4)
15:14:50,003 INFO  [stdout] (pool-9-thread-4) 	 AutomaticSchedulerBean's backgroundProcessing() called....at: Sun Jan 29 15:14:50 IST 2012

These timers are good to perform some background activities like cleaning up some logs …etc.
.
.
Thanks
MiddlewareMagic Team


How to use Scheduler Service of JBoss AS6 for Job Scheduling?

Hi,

Many times it in production scenarios it is required to implement our Jobs to be scheduled and those jobs should run in a frequent interval. JBoss provides a Scheduler service which can be used in order to make it work. The Scheduler directly invokes a callback on an instance of a user defined class, or an operation of a user specified MBean.

JBoss provides an interface “org.jboss.varia.scheduler.Schedulable” This interface defines the manageable interface for a Scheduler Service and allows the client to create a Schedulable instance which is then run by this service at given times (InitialRepetitions). The InitialRepetitions count starts from the value given and in every iteration the value of InitialRepetitions decreases by 1 in every iteration, until the InitialRepetitions value becomes 0.

A developers responsibility is to implement the org.jboss.varia.scheduler.Schedulable interface and then provide the implementation to the void perform(Date timeOfCall, long remaining Repetitions) method. What kind of activities we want to schedule can be written inside the perform() based on our requirement. In this sample we will create a simple Schedulable abd then we will schedule the task for repetition count as 10 and each repetition should happen in the interval of 5 seconds.

Step1). Create a directory somewhere in your file system like “/home/userone/SchedulerDemo/SchedulerDemo”.

Step2). Write the Schedulable class “MySchedulable.java” inside “/home/userone/SchedulerDemo/SchedulerDemo” directory as following:

package test;
import java.util.Date;
import org.jboss.varia.scheduler.Schedulable;
import org.apache.log4j.Logger;
public class MySchedulable implements Schedulable
{
    private static final Logger log = Logger.getLogger(MySchedulable.class);

    private String name;
    private long value;

    public MySchedulable(String name, long value)
    {
        this.name = name;
        this.value = value;
        log.info("nt name: " + name + ", value: " + value);
    }

    public void perform(Date now, long repetitions)
    {
        log.info("perform(), time: " + now +", repetitions: " + repetitions +", name: " + name + ", value: " + value);
    }
}

Step3). Create a scheduler description service XML file as “myScheduler-service.xml” inside “/home/userone/SchedulerDemo/SchedulerDemo” directory as following:

<?xml version="1.0" encoding="UTF-8"?>
<server>
    <mbean code="org.jboss.varia.scheduler.Scheduler" name="jboss.test:service=MyScheduler">
        <attribute name="StartAtStartup">true</attribute>
        <attribute name="SchedulableClass">test.MySchedulable</attribute>
        <attribute name="SchedulableArguments">MySchedulable,100</attribute>
        <attribute name="SchedulableArgumentTypes">java.lang.String,long</attribute>
        <attribute name="InitialStartDate">NOW</attribute>
        <attribute name="SchedulePeriod">5000</attribute>
        <attribute name="InitialRepetitions">10</attribute>
    </mbean>
</server>

Here:
InitialRepetitions=10 means in each repetition of perform() the value will be decreased by 1 and the total repetition will be 10.
MySchedulable,100 are the String and long value which we want to pass to our Schedulable class constructor while initialization.
test.MySchedulable: is the name of our Schedulable class.
java.lang.String,long: Are the argument types of the constructor of our Schedulable class.
NOW : represents the current Data/Time stamp
5000: Is the SchedulePeriod which means the perform() of our schedulable class will be invoked at every 5 seconds interval.
InitialRepetitions=10 means in each repetition of perform() the value will be decreased by 1 and the total repetition will be 10.

Step4). Make sure that your CLASSPATH and PATH is set as following before compiling the above program:

export JAVA_HOME=/home/userone/jdk1.6.0_21
export PATH=$JAVA_HOME/bin:$PATH
export JBOSS_HOME=/home/userone/jboss-5.1/jboss-as
export CLASSPATH=$JBOSS_HOME/common/lib/scheduler-plugin.jar:$JBOSS_HOME/client/log4j.jar:$CLASSPATH:.:

Step5). Now compile the MySchedulable.java as following and then make a Jar of it:

javac -d . MySchedulable.java
jar cvf myscheduler.jar test MySchedulable.java myScheduler-service.xml

Step6). Now deploy the “myscheduler.jar” inside the “$PROFILE/deploy” directory. you will see the following kind of output after deploying the Schedulable Service:

15:02:21,786 INFO  [MySchedulable]
	 name: MySchedulable, value: 100
15:02:22,787 INFO  [MySchedulable] perform(), time: Sun  15:02:22 IST 2011, repetitions: 9, name: MySchedulable, value: 100
15:02:27,787 INFO  [MySchedulable] perform(), time: Sun  15:02:27 IST 2011, repetitions: 8, name: MySchedulable, value: 100
15:02:32,788 INFO  [MySchedulable] perform(), time: Sun  15:02:32 IST 2011, repetitions: 7, name: MySchedulable, value: 100
15:02:37,788 INFO  [MySchedulable] perform(), time: Sun  15:02:37 IST 2011, repetitions: 6, name: MySchedulable, value: 100
15:02:42,789 INFO  [MySchedulable] perform(), time: Sun  15:02:42 IST 2011, repetitions: 5, name: MySchedulable, value: 100
15:02:47,790 INFO  [MySchedulable] perform(), time: Sun  15:02:47 IST 2011, repetitions: 4, name: MySchedulable, value: 100
15:02:52,790 INFO  [MySchedulable] perform(), time: Sun  15:02:52 IST 2011, repetitions: 3, name: MySchedulable, value: 100
15:02:57,791 INFO  [MySchedulable] perform(), time: Sun  15:02:57 IST 2011, repetitions: 2, name: MySchedulable, value: 100
15:03:02,791 INFO  [MySchedulable] perform(), time: Sun  15:03:02 IST 2011, repetitions: 1, name: MySchedulable, value: 100
15:03:07,792 INFO  [MySchedulable] perform(), time: Sun  15:03:07 IST 2011, repetitions: 0, name: MySchedulable, value: 100

Step7). Once the Scheduling is over and repetition is 0 you can restart your Scheduled task using the jmx-console “jboss.test—>service=MyScheduler”
operation “restartSchedule” similarly you can change the schedule interval and repetition etc from jmx-console.

More information about the different attribute which can be defined inside the myScheduler-service.xml file can be found in the following link: http://docs.jboss.org/jbossas/docs/Server_Configuration_Guide/4/html/Scheduling_Tasks-org.jboss.varia.scheduler.Scheduler_.html

.
.
Thanks
Middleware Magic Team


  • Receive FREE Updates


    FREE Email updates of our new posts Enter your email address:



  • Magic Archives

  • Copyright © 2010-2012 Middleware Magic. All rights reserved. | Disclaimer