Quartz 스케줄링 EJB3.0 서비스

11180 단어 quartz
quartz2.0에서는 EJB2.0의 서비스 지원만 지원하지만 EJB3.0에 대한 지원은 제공하지 않기 때문에 사용자 정의 quartz와 관련된job류 EJB3InvokerJob은 EJB3.0에 대한 지원을 제공합니다.
 
EJb3.0 커넥터:
package easyway.tbs.app.ejb;
/**
 * EJB 
 * @author longgangbai
 *
 */
public interface SysTimeEngine {
	
	public String helloword(String username);

}

 
EJb3.0의 서비스 구현 클래스:
package easyway.tbs.app.ejb;


import java.util.Date;

import javax.ejb.Remote;
import javax.ejb.Stateless;

/**
 * EJB 
 * @author longgangbai
 *
 */
@Stateless(name = "SysTimeEngine")
@Remote(SysTimeEngine.class)
public class SysTimeBean implements SysTimeEngine {
	
	public String helloword(String username)
	{
		return "helloworld ,"+username+new Date();
	}
}

 
 
package easyway.tbs.app.ejb;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Hashtable;

import javax.naming.InitialContext;
import javax.naming.NamingException;

import org.quartz.Job;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

/**
 *  EJb3.0 Job 
 * @author longgangbai
 *
 */
public class EJB3InvokerJob implements Job {
	public static final String EJB_JNDI_NAME_KEY = "ejb";

	public static final String EJB_METHOD_KEY = "method";

	public static final String EJB_ARG_TYPES_KEY = "argTypes";

	public static final String EJB_ARGS_KEY = "args";
	
	public static final String INITIAL_CONTEXT_FACTORY = "java.naming.factory.initial";

	public static final String OBJECT_FACTORIES = "java.naming.factory.object";

	public static final String STATE_FACTORIES = "java.naming.factory.state";

	public static final String URL_PKG_PREFIXES = "java.naming.factory.url.pkgs";

	public static final String PROVIDER_URL = "java.naming.provider.url";

	public static final String DNS_URL = "java.naming.dns.url";

	public static final String AUTHORITATIVE = "java.naming.authoritative";

	public static final String BATCHSIZE = "java.naming.batchsize";

	public static final String REFERRAL = "java.naming.referral";

	public static final String SECURITY_PROTOCOL = "java.naming.security.protocol";

	public static final String SECURITY_AUTHENTICATION = "java.naming.security.authentication";

	public static final String SECURITY_PRINCIPAL = "java.naming.security.principal";

	public static final String SECURITY_CREDENTIALS = "java.naming.security.credentials";

	public static final String LANGUAGE = "java.naming.language";

	public static final String APPLET = "java.naming.applet";
	
	public EJB3InvokerJob() {
	}

	/**
	 * 
	 */
	public void execute(JobExecutionContext context)
        throws JobExecutionException
    {
       
        InitialContext jndiContext;
        // job Map
        JobDataMap dataMap = context.getMergedJobDataMap();
        // ejb jndi 
        String ejb = dataMap.getString("ejb");
       // ejb 
        String method= dataMap.getString("method");
        // 
        Object[] arguments = (Object[])(Object[])dataMap.get("args");
        if(arguments == null)
            arguments = new Object[0];
        if(ejb == null)
            throw new JobExecutionException();
        // EJB jndi Context 
        jndiContext = null;
        try
        {
            jndiContext = getInitialContext(dataMap);
        }
        catch(NamingException ne)
        {
            throw new JobExecutionException(ne);
        }
        // EJB 
        Object ejbobject = null;
        try
        {
            ejbobject = jndiContext.lookup(ejb);
        }
        catch(NamingException ne)
        {
            throw new JobExecutionException(ne);
        }
        // 
        Class ejbClass=ejbobject.getClass();
        Method methodExecute = null;
        try
        {
        	  // 
            Class argTypes[] = (Class[])(Class[])dataMap.get("argTypes");
            if(argTypes == null)
            {
                argTypes = new Class[arguments.length];
                for(int i = 0; i < arguments.length; i++)
                    argTypes[i] = arguments[i].getClass();

            }
            // EJB 
            methodExecute = ejbClass.getMethod(method, argTypes);
        }
        catch(NoSuchMethodException nsme)
        {
            throw new JobExecutionException(nsme);
        }
        // EJB 
        try
        {
            Object returnObj = methodExecute.invoke(ejbobject, arguments);
            System.out.println(returnObj);
            context.setResult(returnObj);
        }
        catch(IllegalAccessException iae)
        {
            throw new JobExecutionException(iae);
        }
        catch(InvocationTargetException ite)
        {
            throw new JobExecutionException(ite);
        }
        // 
        if(jndiContext != null)
        {
        	 try
             {
                 jndiContext.close();
             }
             catch(NamingException e) { 
            	 e.printStackTrace();
             }
        }

    }
    /**
     *  EJB 
     * @param jobDataMap
     * @return
     * @throws NamingException
     */
	private InitialContext getInitialContext(JobDataMap jobDataMap)
			throws NamingException {
		Hashtable<String,String> params = new Hashtable<String,String>(3);
		String initialContextFactory = jobDataMap
				.getString(InitialContext.INITIAL_CONTEXT_FACTORY);
		if (initialContextFactory != null)
			params.put(InitialContext.INITIAL_CONTEXT_FACTORY, initialContextFactory);
		String providerUrl = jobDataMap.getString(InitialContext.PROVIDER_URL);
		if (providerUrl != null)
			params.put(InitialContext.PROVIDER_URL, providerUrl);
		String urlpkgprefixes = jobDataMap
				.getString(EJB3InvokerJob.URL_PKG_PREFIXES);
		if (urlpkgprefixes != null)
			params.put(EJB3InvokerJob.URL_PKG_PREFIXES, urlpkgprefixes);
		return params.size() != 0 ? new InitialContext(params)
				: new InitialContext();
	}


}

 
트리거 만들기 및 관련job 작업 호출
package easyway.tbs.app.ejb;

import static org.quartz.DateBuilder.evenMinuteDate;
import static org.quartz.JobBuilder.newJob;
import static org.quartz.TriggerBuilder.newTrigger;

import java.util.Date;

import org.quartz.JobDataMap;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SchedulerFactory;
import org.quartz.Trigger;
import org.quartz.impl.StdSchedulerFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *  EJB3.0 
 * @author longgangbai
 *
 */
public class QuartzEJB {
	public static void main(String[] args) throws SchedulerException {
		Logger log = LoggerFactory.getLogger(QuartzEJB.class);

        log.info("------- Initializing ----------------------");

        // First we must get a reference to a scheduler
        // 
        SchedulerFactory sf = new StdSchedulerFactory();
        // 
        Scheduler sched = sf.getScheduler();

        log.info("------- Initialization Complete -----------");

        // computer a time that is on the next round minute
        Date runTime = evenMinuteDate(new Date());

        log.info("------- Scheduling Job  -------------------");

        // define the job and tie it to our HelloJob class
        // job 
        JobDetail job = newJob(EJB3InvokerJob.class)
            .withIdentity("job1", "group1")
            .build();
        // ejb 
        JobDataMap jobDataMap=job.getJobDataMap();
        jobDataMap.put(EJB3InvokerJob.EJB_JNDI_NAME_KEY, "SysTimeEngine/remote");
        jobDataMap.put(EJB3InvokerJob.EJB_METHOD_KEY, "helloword");
        jobDataMap.put(EJB3InvokerJob.EJB_ARG_TYPES_KEY,new Class[]{ String.class});
        jobDataMap.put(EJB3InvokerJob.EJB_ARGS_KEY,new Object[]{ "wangxingchen"});
        jobDataMap.put(EJB3InvokerJob.INITIAL_CONTEXT_FACTORY, "org.jnp.interfaces.NamingContextFactory");
        jobDataMap.put(EJB3InvokerJob.URL_PKG_PREFIXES,"org.jboss.naming:org.jnp.interfaces");
        jobDataMap.put(EJB3InvokerJob.PROVIDER_URL, "jnp://localhost:1099");
        
        
        log.info(job.getJobDataMap().toString());
        // Trigger the job to run on the next round minute
        // 
        Trigger trigger = newTrigger()
            .withIdentity("trigger1", "group1")
            .startAt(runTime)
            .build();
        
        // Tell quartz to schedule the job using our trigger
        // job 
        sched.scheduleJob(job, trigger);
        log.info(job.getKey() + " will run at: " + runTime);  

        // Start up the scheduler (nothing can actually run until the 
        // scheduler has been started)
        // 
        sched.start();

        log.info("------- Started Scheduler -----------------");

        // wait long enough so that the scheduler as an opportunity to 
        // run the job!
        log.info("------- Waiting 65 seconds... -------------");
        try {
            // wait 65 seconds to show job
            Thread.sleep(65L * 1000L); 
            // executing...
        } catch (Exception e) {
        }

        // shut down the scheduler
        log.info("------- Shutting Down ---------------------");
        sched.shutdown(true);
        log.info("------- Shutdown Complete -----------------");
	}

}

 
 

좋은 웹페이지 즐겨찾기