`
longgangbai
  • 浏览: 7256991 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

Quartz中定时调度EJB3.0服务

 
阅读更多

        在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 -----------------");
	}

}

 

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics