quartz简单应用

Job类:实现Job接口,接口中有一个execute()方法,方法体是你要执行的操作的代码,比如数据库操作,文件操作内容。

JobDetail类:关联一个Job实例。 JobDetail(String JobName,String JobGroup,ClassjobClass)

CronTrigger类:定时触发的类。CronTrigger(String triggerName,String triggerGroup,CronExpression cron)

Scheduler类:SchedulerFactory sf = new StdSchedulerFactory();
     Scheduler s = sf.getScheduler();
     s.scheduleJob(job,trigger);
     s.start();

web应用中使用quartz
可以使用Servlet的 load-on-startup中init方法
使用servlet2.3版本以上的listener
案例:
Job类
package com.hyb.payment;

import com.hyb.payment.PaymentSystem;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

public class PaymentJobToLocalDB implements Job {
	
	  public void execute(JobExecutionContext jec) throws JobExecutionException {
		  	PaymentSystem ps = new PaymentSystem();
			ps.insertIntoAccountInfoTable();
			System.out.println("insert into local database");
	  }
}

JobDetail类与Trigger类

package com.hyb.payment;

import java.text.ParseException;
import org.quartz.CronTrigger;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SchedulerFactory;
import org.quartz.impl.StdSchedulerFactory;
public class PaymentUtilToLocalDB {

	public void run() throws SchedulerException{
		SchedulerFactory schedulerFactory = new StdSchedulerFactory();
		Scheduler scheduler = schedulerFactory.getScheduler();
		JobDetail jobDetail = new JobDetail("job2","group2",PaymentJobToLocalDB.class);
		CronTrigger trigger = null ;
		try {
			// trigger 名字和组 jobdetail名字和组
			//public CronTrigger(String name,String group,String jobName,String jobGroup,String cronExpression)throws ParseException
			trigger = new CronTrigger("trigger2", "group2", "job2","group2", "0 47 16 * * ?");
		} catch (ParseException e) {
			e.printStackTrace();
		}
		scheduler.scheduleJob(jobDetail,trigger);
		scheduler.start();
	}
}

servlet类                               
package com.hyb.payment;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.quartz.SchedulerException;

public class PaymentServlet extends HttpServlet {
	
	public PaymentServlet() {
		super();
	}
	public void destroy() {
		super.destroy(); 
	}
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		this.doPost(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
	}
	public void init() throws ServletException {
		PaymentUtilToRemoteDB pu = new PaymentUtilToRemoteDB();
		try {
			pu.run();
		} catch (SchedulerException e) {
			e.printStackTrace();
		}
		
	}

}

数据库操作类
略…

你可能感兴趣的:(Web,servlet,quartz)