spring+springMVC+mybatis集成Quartz框架(Oracle版本)

说明

本文基于大佬的非maven版脚手架增加的功能,大佬的脚手架是MySQL版本的,并且不再更新了,我对它进行了数据库移植,在下篇文章我会写出Oracle的移植相关细节。大佬的脚手架地址:https://gitee.com/duxiaod/irs,我引入了quartz.jar,关于spring和springmvc+mybatis的配置不详细说,运用了mybatis的generator生成相关的后台代码,前台代码就不写了。

界面展示

数据库表设计

JOB_ID设置为主键

数据序列

create sequence SEQ_TB_JOBS

minvalue 1

maxvalue 9999999999999999999999999999

start with 25

increment by 1

cache 20;

Quartz工具类

public class QuartzManagerUtil {

private static SchedulerFactory schedulerFactory = new StdSchedulerFactory();

/**

* @Description 添加一个定时任务

*

* @param jobName

*            任务名

* @param jobGroupName

*            任务组名

* @param triggerName

*            触发器名

* @param triggerGroupName

*            触发器组名

* @param jobClass

*            任务

* @param cron

*            事件表达式

*/

@SuppressWarnings({ "unchecked", "rawtypes" })

public static void addJob(String jobName, String jobGroupName, String triggerName, String triggerGroupName,

Class jobClass, String cron) {

try {

Scheduler scheduler = schedulerFactory.getScheduler();

// 任务名,任务组,任务执行类

JobDetail jobDetail = JobBuilder.newJob(jobClass).withIdentity(jobName, jobGroupName).build();

// 触发器

TriggerBuilder<Trigger> triggerBuilder = TriggerBuilder.newTrigger();

// 触发器名,触发器组

triggerBuilder.withIdentity(triggerName, triggerGroupName);

triggerBuilder.startNow();

// 触发器时间设定

triggerBuilder.withSchedule(CronScheduleBuilder.cronSchedule(cron));

// 创建Trigger对象

CronTrigger trigger = (CronTrigger) triggerBuilder.build();

// 调度容器设置jobDetail和Trigger

scheduler.scheduleJob(jobDetail, trigger);

// 启动

if (!scheduler.isShutdown()) {

scheduler.start();

}

} catch (SchedulerException e) {

e.printStackTrace();

}

}

/**

* @Description: 修改一个任务的触发时间

*

* @param jobName

*            任务名

* @param jobGroupName

*            任务组名

* @param triggerName

*            触发器名

* @param triggerGroupName

*            触发器组名

* @param cron

*            时间表达式

*/

public static void modifyJobCron(String jobName, String jobGroupName, String triggerName, String triggerGroupName,

String cron) {

try {

Scheduler scheduler = schedulerFactory.getScheduler();

TriggerKey triggerKey = TriggerKey.triggerKey(triggerName, triggerGroupName);

CronTrigger cronTrigger = (CronTrigger) scheduler.getTrigger(triggerKey);

if (cronTrigger == null) {

return;

}

String oldTime = cronTrigger.getCronExpression();

if (!oldTime.equalsIgnoreCase(cron)) {

/** 方式一:调用 rescheduleJob开始 */

// 触发器

TriggerBuilder<Trigger> triggerBuilder = TriggerBuilder.newTrigger();

// 触发器名,触发器组

triggerBuilder.withIdentity(triggerName, triggerGroupName);

triggerBuilder.startNow();

// 触发器时间设定

triggerBuilder.withSchedule(CronScheduleBuilder.cronSchedule(cron));

// 创建Trigger对象

cronTrigger = (CronTrigger) triggerBuilder.build();

// 修改一个任务的触发器时间

scheduler.rescheduleJob(triggerKey, cronTrigger);

/** 方法二:先删除,然后创建一个新的job */

/*

* JobDetail jobDetail =

* scheduler.getJobDetail(JobKey.jobKey(jobName, jobGroupName));

* Class<? extends Job> jobClass = jobDetail.getJobClass();

* removeJob(jobName, jobGroupName, triggerName,

* triggerGroupName); addJob(jobName, jobGroupName, triggerName,

* triggerGroupName, jobClass, cron);

*/

}

} catch (SchedulerException e) {

e.printStackTrace();

}

}

/**

* @Description 删除一个任务

*

* @param jobName

*            任务名

* @param jobGroupName

*            任务组名

* @param triggerName

*            触发器名

* @param triggerGroupName

*            触发器组名

*/

public static void deleteJob(String jobName, String jobGroupName, String triggerName, String triggerGroupName) {

try {

Scheduler scheduler = schedulerFactory.getScheduler();

TriggerKey triggerKey = TriggerKey.triggerKey(triggerName, triggerGroupName);

scheduler.pauseTrigger(triggerKey);// 停止触发器

scheduler.unscheduleJob(triggerKey);// 移除触发器

scheduler.deleteJob(JobKey.jobKey(jobName, jobGroupName));// 删除任务

} catch (SchedulerException e) {

e.printStackTrace();

}

}

/**

* @Description 停用所有任务

*

*/

public static void pauseAllJob() {

try {

Scheduler scheduler = schedulerFactory.getScheduler();

scheduler.pauseAll();

} catch (SchedulerException e) {

e.printStackTrace();

}

}

/**

* @Description 启用所有任务

*/

public static void resumeAll(){

try {

Scheduler scheduler = schedulerFactory.getScheduler();

scheduler.resumeAll();

} catch (SchedulerException e) {

e.printStackTrace();

}

}

/**

* @Description 停用某个任务

*

* @param jobName

*            任务名

* @param jobGroupName

*            任务组名

*/

public static void pauseJob(String jobName, String jobGroupName) {

try {

Scheduler scheduler = schedulerFactory.getScheduler();

scheduler.pauseJob(JobKey.jobKey(jobName, jobGroupName));

} catch (SchedulerException e) {

e.printStackTrace();

}

}

/**

* @Description 启用某个任务

* @param jobName

*            任务名

* @param jobGroupName

*            任务组名

*/

public static void resumeJob(String jobName, String jobGroupName) {

try {

Scheduler scheduler = schedulerFactory.getScheduler();

scheduler.resumeJob(JobKey.jobKey(jobName, jobGroupName));

} catch (SchedulerException e) {

e.printStackTrace();

}

}

/**

* 关闭所有任务

*/

public static void shutDownAll(){

try {

Scheduler scheduler = schedulerFactory.getScheduler();

if(!scheduler.isShutdown()){

scheduler.shutdown();

}

} catch (SchedulerException e) {

e.printStackTrace();

}

}

/**

* 启动所有任务

*/

public static void startAll(){

try {

Scheduler scheduler = schedulerFactory.getScheduler();

scheduler.start();

} catch (SchedulerException e) {

e.printStackTrace();

}

}

/**

* 立即运行一次任务

*/

public static void runOnce(String jobName, String jobGroupName){

try {

Scheduler scheduler = schedulerFactory.getScheduler();

scheduler.triggerJob(JobKey.jobKey(jobName, jobGroupName));

} catch (SchedulerException e) {

e.printStackTrace();

}

}

/**

* 查询某个任务的状态

*/

public static TriggerState getJobStatus(String triggerName, String triggerGroupName) throws SchedulerException{

    Scheduler scheduler = schedulerFactory.getScheduler(); 

    TriggerState state = scheduler.getTriggerState(TriggerKey.triggerKey(triggerName, triggerGroupName));

    return state;

    }

}

JobController代码

@Controller

@RequestMapping("job")

public class JobController {

@Autowired

private JobService jobService;

@RequestMapping("/jobList")

@RequiresPermissions("job:job:list")

public String jobList() {

return "page/job/jobList";

}

@RequestMapping("/getJobList")

@RequiresPermissions("job:job:list")

@ResponseBody

public ResultUtil getJobList(Integer page, Integer limit) {

return jobService.selectJobs(page, limit);

}

@RequestMapping("/getExecutingJobList")

@RequiresPermissions("job:job:list")

@ResponseBody

public ResultUtil getExecutingJobList(Integer page, Integer limit) {

return jobService.getExecutingJobList(page, limit);

}

@SysLog("批量删除指定任务信息")

@RequestMapping("/delJobs/{jobsId}")

@RequiresPermissions("job:job:delete")

@ResponseBody

public ResultUtil delJobs(@PathVariable("jobsId") String jobsId) {

ResultUtil resultUtil = new ResultUtil();

try {

jobService.delJobs(jobsId);

resultUtil.setCode(0);

} catch (Exception e) {

resultUtil.setCode(500);

e.printStackTrace();

}

return resultUtil;

}

@RequestMapping("/addJob")

@RequiresPermissions("job:job:save")

public String addJob(Model model) {

return "page/job/addJob";

}

@SysLog("添加任务信息")

@RequiresPermissions("job:job:save")

@RequestMapping("/toSaveJob")

@ResponseBody

public ResultUtil toSaveJob(TbJobs job) {

List<TbJobs> jobList = jobService.selectByColumn(job);

if (jobList.size() > 0) {

return ResultUtil.ok("添加的任务失败,存在重复字段值");

}

if (!CronExpression.isValidExpression(job.getCron())) {

return ResultUtil.ok("添加任务失败,时间表达式格式不正确");

}

try {

QuartzManagerUtil.addJob(job.getJobName(), job.getJobGroupName(), job.getTriggerName(),

job.getJobGroupName(), Class.forName(job.getClassName()), job.getCron());

} catch (ClassNotFoundException e) {

e.printStackTrace();

return ResultUtil.error("添加失败,执行类不存在");

}

job.setStatus("0");

jobService.insertJob(job);

return ResultUtil.ok("添加任务成功");

}

@RequestMapping("/editJob/{jobId}")

@RequiresPermissions("job:job:update")

public String editJob(Model model, @PathVariable("jobId") String jobId) {

TbJobs job = jobService.selectByPrimaryKey(Long.parseLong(jobId));

model.addAttribute("job", job);

return "page/job/editJob";

}

@SysLog("修改任务信息")

@RequiresPermissions("job:job:update")

@RequestMapping("/toEditJob")

@ResponseBody

public ResultUtil toEditJob(TbJobs job) {

job.setStatus("0");

jobService.updateByPrimaryKey(job);

QuartzManagerUtil.modifyJobCron(job.getJobName(), job.getJobGroupName(), job.getTriggerName(),

job.getTriggerGroupName(), job.getCron());

QuartzManagerUtil.resumeJob(job.getJobName(), job.getJobGroupName());

return ResultUtil.ok("修改任务成功");

}

@SysLog("启用任务")

@RequestMapping("/resumeJob/{jobId}")

@ResponseBody

public ResultUtil resumeJob(@PathVariable("jobId") String jobId) {

TbJobs job = jobService.selectByPrimaryKey(Long.parseLong(jobId));

StdSchedulerFactory schedulerFactory = new StdSchedulerFactory();

try {

Scheduler scheduler = schedulerFactory.getScheduler();

TriggerState state = scheduler

.getTriggerState(TriggerKey.triggerKey(job.getTriggerName(), job.getTriggerGroupName()));

if (state.equals(TriggerState.NONE)) {

QuartzManagerUtil.addJob(job.getJobName(), job.getJobGroupName(), job.getTriggerName(),

job.getJobGroupName(), Class.forName(job.getClassName()), job.getCron());

} else {

QuartzManagerUtil.resumeJob(job.getJobName(), job.getJobGroupName());

}

} catch (SchedulerException e) {

e.printStackTrace();

} catch (ClassNotFoundException e) {

e.printStackTrace();

return ResultUtil.error("添加失败,执行类不存在");

}

job.setStatus("0");

jobService.updateByPrimaryKey(job);

return ResultUtil.ok();

}

@SysLog("停用任务")

@RequestMapping("/pauseJob/{jobId}")

@ResponseBody

public ResultUtil pauseJob(@PathVariable("jobId") String jobId) {

TbJobs job = jobService.selectByPrimaryKey(Long.parseLong(jobId));

QuartzManagerUtil.pauseJob(job.getJobName(), job.getJobGroupName());

job.setStatus("1");

jobService.updateByPrimaryKey(job);

return ResultUtil.ok();

}

@SysLog("立即运行一次任务")

@RequestMapping("/runOnce/{jobId}")

@ResponseBody

public ResultUtil runOnce(@PathVariable("jobId") String jobId) {

TbJobs job = jobService.selectByPrimaryKey(Long.parseLong(jobId));

QuartzManagerUtil.runOnce(job.getJobName(), job.getJobGroupName());

return ResultUtil.ok();

}

}

JobService代码

public interface JobService {

//获取所有任务

public ResultUtil selectJobs(Integer page,Integer limit);

//获取所有执行中的任务

public ResultUtil getExecutingJobList(Integer page,Integer limit);

//批量删除指定任务

public void delJobs(String jobsId);

//插入任务

public void insertJob(TbJobs job);

//根据任务Id查找任务

public TbJobs selectByPrimaryKey(Long jobId);

//根据任务ID更新任务信息

public void updateByPrimaryKey(TbJobs job);

//根据字段查找插入的任务是否有重复字段值

public List<TbJobs> selectByColumn(TbJobs job);

//根据字段查找插入的任务是否有重复字段值2

public TbJobs selectByColumn2(TbJobs job);

//查找数据库中所有的任务信息

public List<TbJobs> selectAllJobs();

public List<TbJobs> selectByExample(TbJobsExample example);

}

JobServiceImpl代码

@Service

public class JobServiceImpl implements JobService {

@Autowired

private TbJobsMapper jobMapper;

@Override

public ResultUtil selectJobs(Integer page, Integer limit) {

PageHelper.startPage(page, limit);

TbJobsExample example = new TbJobsExample();

List<TbJobs> list = jobMapper.selectByExample(example);

PageInfo<TbJobs> pageInfo = new PageInfo<TbJobs>(list);

ResultUtil resultUtil = new ResultUtil();

resultUtil.setCode(0);

resultUtil.setCount(pageInfo.getTotal());

resultUtil.setData(pageInfo.getList());

return resultUtil;

}

@Override

public ResultUtil getExecutingJobList(Integer page, Integer limit) {

PageHelper.startPage(page, limit);

List<TbJobs> jobList = selectAllJobs();

List<TbJobs> list = new ArrayList<>();

StdSchedulerFactory schedulerFactory = new StdSchedulerFactory();

Scheduler scheduler = null;

try {

scheduler = schedulerFactory.getScheduler();

for (TbJobs job : jobList) {

if (job.getStatus().equals("0")) {

TriggerState state = scheduler

.getTriggerState(TriggerKey.triggerKey(job.getTriggerName(), job.getTriggerGroupName()));

if (state.equals(TriggerState.NORMAL)) {

list.add(job);

}

}

}

} catch (SchedulerException e) {

e.printStackTrace();

}

PageInfo<TbJobs> pageInfo = new PageInfo<TbJobs>(list);

ResultUtil resultUtil = new ResultUtil();

resultUtil.setCode(0);

resultUtil.setCount(pageInfo.getTotal());

resultUtil.setData(pageInfo.getList());

return resultUtil;

}

@Override

public void delJobs(String jobsId) {

String[] jobIds = jobsId.split(",");

for (String jobId : jobIds) {

TbJobs job = selectByPrimaryKey(Long.parseLong(jobId));

QuartzManagerUtil.deleteJob(job.getJobName(), job.getJobGroupName(), job.getTriggerName(),

job.getTriggerGroupName());

jobMapper.deleteByPrimaryKey(Long.parseLong(jobId));

}

}

@Override

public void insertJob(TbJobs job) {

jobMapper.insert(job);

}

@Override

public TbJobs selectByPrimaryKey(Long jobId) {

return jobMapper.selectByPrimaryKey(jobId);

}

@Override

public void updateByPrimaryKey(TbJobs job) {

jobMapper.updateByPrimaryKey(job);

}

@Override

public List<TbJobs> selectByColumn(TbJobs job) {

return jobMapper.selectByColumn(job);

}

@Override

public TbJobs selectByColumn2(TbJobs job) {

return jobMapper.selectByColumn2(job);

}

@Override

public List<TbJobs> selectAllJobs() {

return jobMapper.selectAllJobs();

}

public List<TbJobs> selectByExample(TbJobsExample example) {

return jobMapper.selectByExample(example);

}

}

JobMapper代码

public interface TbJobsMapper {

    int countByExample(TbJobsExample example);

    int deleteByExample(TbJobsExample example);

    int deleteByPrimaryKey(Long jobId);

    int insert(TbJobs record);

    int insertSelective(TbJobs record);

    List<TbJobs> selectByExample(TbJobsExample example);

    TbJobs selectByPrimaryKey(Long jobId);


    List<TbJobs> selectByColumn(TbJobs job);


    TbJobs selectByColumn2(TbJobs job);


    List<TbJobs> selectAllJobs();

    int updateByExampleSelective(@Param("record") TbJobs record, @Param("example") TbJobsExample example);

    int updateByExample(@Param("record") TbJobs record, @Param("example") TbJobsExample example);

    int updateByPrimaryKeySelective(TbJobs record);

    int updateByPrimaryKey(TbJobs record);

}

JobMapper.xml代码

<?xml version="1.0" encoding="UTF-8" ?>

<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >

<mapper namespace="com.irs.mapper.TbJobsMapper" >

  <resultMap id="BaseResultMap" type="com.irs.pojo.TbJobs" >

    <id column="JOB_ID" property="jobId" jdbcType="BIGINT" />

    <result column="JOB_NAME" property="jobName" jdbcType="VARCHAR" />

    <result column="JOB_GROUP_NAME" property="jobGroupName" jdbcType="VARCHAR" />

    <result column="TRIGGER_NAME" property="triggerName" jdbcType="VARCHAR" />

    <result column="TRIGGER_GROUP_NAME" property="triggerGroupName" jdbcType="VARCHAR" />

    <result column="CRON" property="cron" jdbcType="VARCHAR" />

    <result column="CLASS_NAME" property="className" jdbcType="VARCHAR" />

    <result column="STATUS" property="status" jdbcType="VARCHAR" />

  </resultMap>

  <sql id="Example_Where_Clause" >

    <where >

      <foreach collection="oredCriteria" item="criteria" separator="or" >

        <if test="criteria.valid" >

          <trim prefix="(" suffix=")" prefixOverrides="and" >

            <foreach collection="criteria.criteria" item="criterion" >

              <choose >

                <when test="criterion.noValue" >

                  and ${criterion.condition}

                </when>

                <when test="criterion.singleValue" >

                  and ${criterion.condition} #{criterion.value}

                </when>

                <when test="criterion.betweenValue" >

                  and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}

                </when>

                <when test="criterion.listValue" >

                  and ${criterion.condition}

                  <foreach collection="criterion.value" item="listItem" open="(" close=")" separator="," >

                    #{listItem}

                  </foreach>

                </when>

              </choose>

            </foreach>

          </trim>

        </if>

      </foreach>

    </where>

  </sql>

  <sql id="Update_By_Example_Where_Clause" >

    <where >

      <foreach collection="example.oredCriteria" item="criteria" separator="or" >

        <if test="criteria.valid" >

          <trim prefix="(" suffix=")" prefixOverrides="and" >

            <foreach collection="criteria.criteria" item="criterion" >

              <choose >

                <when test="criterion.noValue" >

                  and ${criterion.condition}

                </when>

                <when test="criterion.singleValue" >

                  and ${criterion.condition} #{criterion.value}

                </when>

                <when test="criterion.betweenValue" >

                  and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}

                </when>

                <when test="criterion.listValue" >

                  and ${criterion.condition}

                  <foreach collection="criterion.value" item="listItem" open="(" close=")" separator="," >

                    #{listItem}

                  </foreach>

                </when>

              </choose>

            </foreach>

          </trim>

        </if>

      </foreach>

    </where>

  </sql>

  <sql id="Base_Column_List" >

    JOB_ID, JOB_NAME, JOB_GROUP_NAME, TRIGGER_NAME, TRIGGER_GROUP_NAME, CRON, CLASS_NAME,

    STATUS

  </sql>

  <select id="selectByExample" resultMap="BaseResultMap" parameterType="com.irs.pojo.TbJobsExample" >

    select

    <if test="distinct" >

      distinct

    </if>

    <include refid="Base_Column_List" />

    from tb_jobs

    <if test="_parameter != null" >

      <include refid="Example_Where_Clause" />

    </if>

    <if test="orderByClause != null" >

      order by ${orderByClause}

    </if>

  </select>

  <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Long" >

    select

    <include refid="Base_Column_List" />

    from tb_jobs

    where JOB_ID = #{jobId,jdbcType=BIGINT}

  </select>

  <select id="selectAllJobs" resultMap="BaseResultMap">

    select

    <include refid="Base_Column_List" />

    from TB_JOBS

    where 1=1

  </select>

  <select id="selectByColumn" resultMap="BaseResultMap" parameterType="com.irs.pojo.TbJobs" >

    select

    <include refid="Base_Column_List" />

    from TB_JOBS

    where 1=1

      <if test="jobName!=null">

      and JOB_NAME = #{jobName,jdbcType=VARCHAR}

      </if>

      <if test="jobGroupName!=null">

      and JOB_GROUP_NAME = #{jobGroupName,jdbcType=VARCHAR}

      </if>

      <if test="triggerName!=null">

      and TRIGGER_NAME = #{triggerName,jdbcType=VARCHAR}

      </if>

      <if test="triggerGroupName!=null">

      and TRIGGER_GROUP_NAME = #{triggerGroupName,jdbcType=VARCHAR}

      </if>

      <if test="className!=null">

      and CLASS_NAME = #{className,jdbcType=VARCHAR}

      </if>

  </select>

  <select id="selectByColumn2" resultMap="BaseResultMap" parameterType="com.irs.pojo.TbJobs" >

    select

    <include refid="Base_Column_List" />

    from TB_JOBS

    where 1=1

      <if test="jobName!=null">

      and JOB_NAME = #{jobName,jdbcType=VARCHAR}

      </if>

      <if test="jobGroupName!=null">

      and JOB_GROUP_NAME = #{jobGroupName,jdbcType=VARCHAR}

      </if>

      <if test="triggerName!=null">

      and TRIGGER_NAME = #{triggerName,jdbcType=VARCHAR}

      </if>

      <if test="triggerGroupName!=null">

      and TRIGGER_GROUP_NAME = #{triggerGroupName,jdbcType=VARCHAR}

      </if>

      <if test="className!=null">

      and CLASS_NAME = #{className,jdbcType=VARCHAR}

      </if>

  </select>

  <delete id="deleteByPrimaryKey" parameterType="java.lang.Long" >

    delete from tb_jobs

    where JOB_ID = #{jobId,jdbcType=BIGINT}

  </delete>

  <delete id="deleteByExample" parameterType="com.irs.pojo.TbJobsExample" >

    delete from tb_jobs

    <if test="_parameter != null" >

      <include refid="Example_Where_Clause" />

    </if>

  </delete>

  <insert id="insert" parameterType="com.irs.pojo.TbJobs" >

    insert into tb_jobs (JOB_ID, JOB_NAME, JOB_GROUP_NAME,

      TRIGGER_NAME, TRIGGER_GROUP_NAME, CRON,

      CLASS_NAME, STATUS)

    values (#{jobId,jdbcType=BIGINT}, #{jobName,jdbcType=VARCHAR}, #{jobGroupName,jdbcType=VARCHAR},

      #{triggerName,jdbcType=VARCHAR}, #{triggerGroupName,jdbcType=VARCHAR}, #{cron,jdbcType=VARCHAR},

      #{className,jdbcType=VARCHAR}, #{status,jdbcType=VARCHAR})

  </insert>

  <insert id="insertSelective" parameterType="com.irs.pojo.TbJobs" >

    insert into tb_jobs

    <trim prefix="(" suffix=")" suffixOverrides="," >

      <if test="jobId != null" >

        JOB_ID,

      </if>

      <if test="jobName != null" >

        JOB_NAME,

      </if>

      <if test="jobGroupName != null" >

        JOB_GROUP_NAME,

      </if>

      <if test="triggerName != null" >

        TRIGGER_NAME,

      </if>

      <if test="triggerGroupName != null" >

        TRIGGER_GROUP_NAME,

      </if>

      <if test="cron != null" >

        CRON,

      </if>

      <if test="className != null" >

        CLASS_NAME,

      </if>

      <if test="status != null" >

        STATUS,

      </if>

    </trim>

    <trim prefix="values (" suffix=")" suffixOverrides="," >

      <if test="jobId != null" >

        #{jobId,jdbcType=BIGINT},

      </if>

      <if test="jobName != null" >

        #{jobName,jdbcType=VARCHAR},

      </if>

      <if test="jobGroupName != null" >

        #{jobGroupName,jdbcType=VARCHAR},

      </if>

      <if test="triggerName != null" >

        #{triggerName,jdbcType=VARCHAR},

      </if>

      <if test="triggerGroupName != null" >

        #{triggerGroupName,jdbcType=VARCHAR},

      </if>

      <if test="cron != null" >

        #{cron,jdbcType=VARCHAR},

      </if>

      <if test="className != null" >

        #{className,jdbcType=VARCHAR},

      </if>

      <if test="status != null" >

        #{status,jdbcType=VARCHAR},

      </if>

    </trim>

  </insert>

  <select id="countByExample" parameterType="com.irs.pojo.TbJobsExample" resultType="java.lang.Integer" >

    select count(*) from tb_jobs

    <if test="_parameter != null" >

      <include refid="Example_Where_Clause" />

    </if>

  </select>

  <update id="updateByExampleSelective" parameterType="map" >

    update tb_jobs

    <set >

      <if test="record.jobId != null" >

        JOB_ID = #{record.jobId,jdbcType=BIGINT},

      </if>

      <if test="record.jobName != null" >

        JOB_NAME = #{record.jobName,jdbcType=VARCHAR},

      </if>

      <if test="record.jobGroupName != null" >

        JOB_GROUP_NAME = #{record.jobGroupName,jdbcType=VARCHAR},

      </if>

      <if test="record.triggerName != null" >

        TRIGGER_NAME = #{record.triggerName,jdbcType=VARCHAR},

      </if>

      <if test="record.triggerGroupName != null" >

        TRIGGER_GROUP_NAME = #{record.triggerGroupName,jdbcType=VARCHAR},

      </if>

      <if test="record.cron != null" >

        CRON = #{record.cron,jdbcType=VARCHAR},

      </if>

      <if test="record.className != null" >

        CLASS_NAME = #{record.className,jdbcType=VARCHAR},

      </if>

      <if test="record.status != null" >

        STATUS = #{record.status,jdbcType=VARCHAR},

      </if>

    </set>

    <if test="_parameter != null" >

      <include refid="Update_By_Example_Where_Clause" />

    </if>

  </update>

  <update id="updateByExample" parameterType="map" >

    update tb_jobs

    set JOB_ID = #{record.jobId,jdbcType=BIGINT},

      JOB_NAME = #{record.jobName,jdbcType=VARCHAR},

      JOB_GROUP_NAME = #{record.jobGroupName,jdbcType=VARCHAR},

      TRIGGER_NAME = #{record.triggerName,jdbcType=VARCHAR},

      TRIGGER_GROUP_NAME = #{record.triggerGroupName,jdbcType=VARCHAR},

      CRON = #{record.cron,jdbcType=VARCHAR},

      CLASS_NAME = #{record.className,jdbcType=VARCHAR},

      STATUS = #{record.status,jdbcType=VARCHAR}

    <if test="_parameter != null" >

      <include refid="Update_By_Example_Where_Clause" />

    </if>

  </update>

  <update id="updateByPrimaryKeySelective" parameterType="com.irs.pojo.TbJobs" >

    update tb_jobs

    <set >

      <if test="jobName != null" >

        JOB_NAME = #{jobName,jdbcType=VARCHAR},

      </if>

      <if test="jobGroupName != null" >

        JOB_GROUP_NAME = #{jobGroupName,jdbcType=VARCHAR},

      </if>

      <if test="triggerName != null" >

        TRIGGER_NAME = #{triggerName,jdbcType=VARCHAR},

      </if>

      <if test="triggerGroupName != null" >

        TRIGGER_GROUP_NAME = #{triggerGroupName,jdbcType=VARCHAR},

      </if>

      <if test="cron != null" >

        CRON = #{cron,jdbcType=VARCHAR},

      </if>

      <if test="className != null" >

        CLASS_NAME = #{className,jdbcType=VARCHAR},

      </if>

      <if test="status != null" >

        STATUS = #{status,jdbcType=VARCHAR},

      </if>

    </set>

    where JOB_ID = #{jobId,jdbcType=BIGINT}

  </update>

  <update id="updateByPrimaryKey" parameterType="com.irs.pojo.TbJobs" >

    update tb_jobs

    set JOB_NAME = #{jobName,jdbcType=VARCHAR},

      JOB_GROUP_NAME = #{jobGroupName,jdbcType=VARCHAR},

      TRIGGER_NAME = #{triggerName,jdbcType=VARCHAR},

      TRIGGER_GROUP_NAME = #{triggerGroupName,jdbcType=VARCHAR},

      CRON = #{cron,jdbcType=VARCHAR},

      CLASS_NAME = #{className,jdbcType=VARCHAR},

      STATUS = #{status,jdbcType=VARCHAR}

    where JOB_ID = #{jobId,jdbcType=BIGINT}

  </update>

</mapper>

Tomcat启动就加载数据库中的任务

public class QuartzStartInitialize implements ApplicationListener<ContextRefreshedEvent>{

@Autowired

private JobService jobService;

private  static  final Logger logger = LoggerFactory.getLogger(QuartzStartInitialize.class); 

@Override

public void onApplicationEvent(ContextRefreshedEvent event) {

if(event.getApplicationContext().getParent()==null){

List<TbJobs> jobList = jobService.selectAllJobs();

if (jobList.size() > 0) {

for (TbJobs job : jobList) {

if (job.getStatus().equals("0")) {

if (CronExpression.isValidExpression(job.getCron())) {

QuartzManagerUtil.deleteJob(job.getJobName(), job.getJobGroupName(), job.getTriggerName(),

job.getTriggerGroupName());

try {

QuartzManagerUtil.addJob(job.getJobName(), job.getJobGroupName(), job.getTriggerName(),

job.getTriggerGroupName(), Class.forName(job.getClassName()), job.getCron());

logger.info("定时任务"+job.getJobName()+": 开始启动");

} catch (ClassNotFoundException e) {

e.printStackTrace();

}

}else{

logger.warn("定时任务"+job.getJobName()+": cron表达式不正确");

}

}

}

}

}

}

}

Spring配置

将上面的QuartzStartInitialize 类配置到applicationContext-dao.xml中。

<bean class="com.irs.annotation.QuartzStartInitialize" />

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 205,033评论 6 478
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 87,725评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 151,473评论 0 338
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,846评论 1 277
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,848评论 5 368
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,691评论 1 282
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,053评论 3 399
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,700评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 42,856评论 1 300
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,676评论 2 323
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,787评论 1 333
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,430评论 4 321
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,034评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,990评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,218评论 1 260
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,174评论 2 352
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,526评论 2 343

推荐阅读更多精彩内容