欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

servlet整合quartz:servlet中使用quartz,服务器启动时加载任务

程序员文章站 2024-02-01 16:22:10
servlet整合quartz:servlet中使用quartz,服务器启动时加载任务一、写一个servlet实现ServletContextListener接口代码如下:package jobs;import javax.servlet.ServletContextEvent;import javax.servlet.ServletContextListener;import org.quartz.CronScheduleBuilder;import org.quartz.CronTrig...

servlet整合quartz:servlet中使用quartz,服务器启动时加载任务

一、写一个servlet实现ServletContextListener接口
代码如下:

package jobs;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import org.quartz.CronScheduleBuilder;
import org.quartz.CronTrigger;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.TriggerBuilder;
import org.quartz.impl.StdSchedulerFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
 * @Description: 任务调度监听器:服务器启动时加载定时任务
 * @author Emmanuev.yi
 *
 */
public class JobsListener implements ServletContextListener {
	private static final Logger logger = LoggerFactory.getLogger(JobsListener.class);
	@Override
	public void contextInitialized(ServletContextEvent sce) {
		logger.info("------------The listener is in effect!!!------------");
		try {
			//任务调度工厂
			Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();
			
			//任务实例
			//定时任务1
			JobDetail jobDetail1 = JobBuilder
					.newJob(InitTabDataJob.class)
					.withIdentity("initTabDataJob", "group1")
					.build();
			
			//定时任务2
			JobDetail jobDetail2 = JobBuilder
				.newJob(EveryHourUpdadteJob.class)
				.withIdentity("everyHourUpdadteJob", "group1")
				.build();
			
			
			//任务触发器:
			
			//任务1(初始化表格)触发器
			CronTrigger cronTrigger1 = TriggerBuilder
				.newTrigger()
				.withIdentity("ehujTrigger", "Tgroup1")
				.startNow()
				.withSchedule(CronScheduleBuilder.cronSchedule("0 0 8 * * ?"))	//每天8点触发	0 0 8 * * ?
				//.withSchedule(CronScheduleBuilder.cronSchedule("0 45 16 * * ?"))
				.build();
			
			
			
			//任务2(每小时更新数据)触发器
			CronTrigger cronTrigger2 = TriggerBuilder.newTrigger()
				.withIdentity("itdj", "Tgroup2")
				.startNow()
				//.withSchedule(CronScheduleBuilder.cronSchedule("0 */1 * * * ?")) //每小时10分触发,每隔半小时触发一次	0 10/30 * * * ?		0/5 * * * * ?
				.withSchedule(CronScheduleBuilder.cronSchedule("0 0 14 * * ?"))
				.build();	
			
			//添加任务调度
			scheduler.scheduleJob(jobDetail1, cronTrigger1);
			scheduler.scheduleJob(jobDetail2, cronTrigger2);
			//启动调度器
			scheduler.start();
		} catch (SchedulerException e) {
			e.printStackTrace();
		}
	}

	
	/**
	 * 任务销毁
	 */
	@Override
	public void contextDestroyed(ServletContextEvent sce) {
		sce.getServletContext().log("timer task over !!!");
	}

	
}


二、在web.xml文件中配置监听器类,将以上的JobsListener 类配置其中,以确保能在服务器启动时加载任务。以下为配置信息。

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>OEE</display-name>
  <listener>
    <listener-class>jobs.JobsListener</listener-class>
  </listener>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
</web-app>

三、书写具体任务
1、任务1:InitTabDataJob

package jobs;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Date;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import cn.itcast.jdbc.JdbcUtils;
import utils.CommonUtil;
import utils.FileUtil;

/**
 * 初始化表数据任务
 * @author Emmanuev.yi
 *
 */
public class InitTabDataJob implements Job{
	private static final Logger logger = LoggerFactory.getLogger(InitTabDataJob.class);
	/**
	 * @Description: 任务执行方法
	 */
	public void execute(JobExecutionContext arg0) throws JobExecutionException {
		//Logger
		logger.info("table initialization beginning......");
		initTab_execute();
	}

	
	/**
	 * @Description: 初始化表格:批量插入初始化数据,每天8点执行一次
	 */
	public void initTab_execute() {
		//这里是业务代码,就不写了......
	}
}

2、任务2:EveryHourUpdadteJob

package jobs;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Set;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;
import org.dom4j.DocumentException;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import entity.EveryHourRatio;
import entity.MachineRunInfo;
import utils.CommonUtil;
import utils.FileUtil;
import utils.JdbcUtils;

/**
 * 每小时插入机台效率的任务
 * @author Emmanuev.yi
 *
 */
public class EveryHourUpdadteJob implements Job{
	private static final Logger logger = LoggerFactory.getLogger(EveryHourUpdadteJob.class);
	private static final String FORMAT = "yyyy-MM-dd HH:mm:ss";
	private String str_dayShiftStart;	//开始时间
	private String str_dayShiftEnd;		//结束时间
	private FileUtil fu = new FileUtil();
	
	//构造代码块:创建本类对象时进行初始化参数
	{
		Date currentDate = new Date();
		String strCurrentDate = CommonUtil.dateToTime(currentDate, "yyyy-MM-dd");
		
		Calendar c = Calendar.getInstance();
		c.setTime(currentDate);
		int hour = c.get(Calendar.HOUR_OF_DAY);
		
		/*
		 * 根据时间当前时间点确定查询的[开始时间]和[结束时间]
		 * 8~23:
		 * 	查询时间区间:当天8点~当天+1天8点
		 * 0~8:
		 * 	查询时间区间:当天-1天8点~当天8点
		 */
		if(hour >= 8 && hour <= 23) {
			str_dayShiftStart = strCurrentDate+" 08:00:00";
			str_dayShiftEnd = CommonUtil.arithmeticTime_day(str_dayShiftStart, FORMAT, 1);
		}else if(hour >= 0 && hour < 8) {
			str_dayShiftEnd = strCurrentDate+" 08:00:00";
			str_dayShiftStart = CommonUtil.arithmeticTime_day(str_dayShiftEnd, FORMAT, -1);
		}
	}
	
	@Override
	public void execute(JobExecutionContext arg0) throws JobExecutionException {
		try {
			logger.info("update datas beginning......");
			update_execute();
		} catch (Exception e) {
			e.printStackTrace();
		} 
	}
	
	
	
	//更新数据
	public void update_execute() throws SQLException, ParseException, DocumentException {
		//这里是业务代码,就不写了......
	}
}

四、结语
没什么好说的,就是这么简单,祝大家编码愉快!

本文地址:https://blog.csdn.net/yimianzhen/article/details/107345611