实现的功能 :1,每次添加一个场景,这个场景有个备份策略,保存后需要按照这个输入的时间定时往数据库存历史数据。


                     新增场景的的时候有个配置时间的选项(配置cron表达式),备份策略定义的时间就是定时的时间。


springboot整合定时任务存储数据库 spring定时任务数据库配置_spring

(1) 版本:spring 3.1.3.RELEASE  quartz:2.2.1(版本不同可能会报错,详情请看链接,我根据链接的实现的自己的功能,是缩减版本,只是为自己做个笔记) 

详细链接:http://www.jb51.net/article/107339.htm


1.在配置文件中配置context-collie-scene.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="sceneService" class="com.surekam.collie.scene.service.impl.SceneServiceImpl">
        <property name="sceneDao" ref="sceneDao"/>
    </bean>

    <bean id="sceneDao" class="com.surekam.collie.scene.dao.impl.SceneDaoImpl">
        <property name="sessionFactory" ref="sessionFactory"/>
        <property name="jdbcBaseDAO" ref="jdbcBaseDAO"/>
    </bean>

    <!--<!– 调度工厂 –>-->
    <bean id="scheduler" class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
    </bean>
<bean id="timeTask" class="com.surekam.collie.scene.finalTest.TimeTask">
        <property name="scheduler" ref="scheduler"/>
    </bean>
</beans>

(2)主要实现的工具类:

package com.surekam.collie.scene.finalTest;

import com.surekam.collie.scene.bean.ScheduleJob;
import com.surekam.collie.scene.service.SceneService;
import com.surekam.platform.core.container.ApplicationContext;
import com.surekam.platform.core.container.spring.LazyInitBean;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.quartz.*;

import java.util.List;


public class TimeTask implements LazyInitBean {
    private static final Log log = LogFactory.getLog(TimeTask.class);

    private Scheduler scheduler; //配置文件中要注入的

    public void setScheduler(Scheduler scheduler) {
        this.scheduler = scheduler;
    }

    /**
     * 增加和修改任务
     */
    public void scheduleJobTest() {

        SceneService sceneService = (SceneService) ApplicationContext
                .getInstance().getBizComponent("sceneService");//注入自己service
        //这里获取任务信息数据,其他的都是固定的
        List<ScheduleJob> jobList = sceneService.getAllJob();

        for (ScheduleJob job : jobList) {

            TriggerKey triggerKey = TriggerKey.triggerKey(job.getJobName(), job.getJobGroup());

            //获取trigger,即在spring配置文件中定义的 bean id="myTrigger"
            CronTrigger trigger = null;
            try {
                trigger = (CronTrigger) scheduler.getTrigger(triggerKey);
            } catch (SchedulerException e) {
                e.printStackTrace();
            }

            //不存在,创建一个
            if (null == trigger) {
                JobDetail jobDetail = JobBuilder.newJob(QuartzJobFactory.class)
                        .withIdentity(job.getJobName(), job.getJobGroup()).build();
                jobDetail.getJobDataMap().put("scheduleJob", job);

                //表达式调度构建器
                CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(job
                        .getCronExpression());

                //按新的cronExpression表达式构建一个新的trigger
                trigger = TriggerBuilder.newTrigger().withIdentity(job.getJobName(), job.getJobGroup()).withSchedule(scheduleBuilder).build();

                try {
                    scheduler.scheduleJob(jobDetail, trigger);
                } catch (SchedulerException e) {
                    e.printStackTrace();
                }
            } else {
                // Trigger已存在,那么更新相应的定时设置
                //表达式调度构建器
                CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(job
                        .getCronExpression());

                //按新的cronExpression表达式重新构建trigger
                trigger = trigger.getTriggerBuilder().withIdentity(triggerKey)
                        .withSchedule(scheduleBuilder).build();

                //按新的trigger重新设置job执行
                try {
                    scheduler.rescheduleJob(triggerKey, trigger);
                } catch (SchedulerException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 删除scheduleJob
     */
    public  void deleteScheduleJob(String jobName,String jobId){
//        Scheduler scheduler = schedulerFactoryBean.getScheduler();

        JobKey jobKey = JobKey.jobKey(jobName,jobId);
        try {
            scheduler.deleteJob(jobKey);
        } catch (SchedulerException e) {
            e.printStackTrace();
        }

    }
/**
*让容器初始化的时候就去执行
*/
    @Override
    public void afterContainerInit() {
        scheduleJobTest();
    }
}



(3)创建任务bean 从id 到cronExpression是比较需要的,后面属性根据自己需要加,数据库设置建立对应的表



package com.surekam.collie.scene.bean;

/**
 * 计划任务信息
 *
 * @author tq
 * @date 2016/5/1
 */
public class ScheduleJob {
    /** 主键id */
    private String id;
    /** 任务id */
    private String jobId;
    /** 任务名称 */
    private String jobName;
    /** 任务分组 */
    private String jobGroup;
    /** 任务状态 0禁用 1启用 2删除*/
    private String jobStatus;
    /** 任务运行时间表达式 */
    private String cronExpression;
    /** 任务描述 */
    private String desc;
    /** sceneID*/
    private String sceneId;
    /**changTime*/
    private String changTime;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getChangTime() {
        return changTime;
    }

    public void setChangTime(String changTime) {
        this.changTime = changTime;
    }

    public String getSceneId() {
        return sceneId;
    }

    public void setSceneId(String sceneId) {
        this.sceneId = sceneId;
    }



    public String getJobId() {
        return jobId;
    }

    public void setJobId(String jobId) {
        this.jobId = jobId;
    }

    public String getJobName() {
        return jobName;
    }

    public void setJobName(String jobName) {
        this.jobName = jobName;
    }

    public String getJobGroup() {
        return jobGroup;
    }

    public void setJobGroup(String jobGroup) {
        this.jobGroup = jobGroup;
    }

    public String getJobStatus() {
        return jobStatus;
    }

    public void setJobStatus(String jobStatus) {
        this.jobStatus = jobStatus;
    }

    public String getCronExpression() {
        return cronExpression;
    }

    public void setCronExpression(String cronExpression) {
        this.cronExpression = cronExpression;
    }

    public String getDesc() {
        return desc;
    }

    public void setDesc(String desc) {
        this.desc = desc;
    }
}


(4)基本上需要的就写完了,下面的是调用,下面的

execute方法就是会去自动执行的方法,你要写的业务就写在这个方法里面。

大概流程就是:服务器启动后,初始化会通过配置文件的调度工厂,哗啦啦我也不懂,然后

scheduleJobTest() {

        SceneService sceneService = (SceneService) ApplicationContext
                .getInstance().getBizComponent("sceneService");//注入自己service
        //这里获取任务信息数据,其他的都是固定的
        List<ScheduleJob> jobList = sceneService.getAllJob();
通过自己写的去数据库的schdulejob表中获取所有的任务,根据jobid jobName ,和jobGroup确定任务,然后根据cronExpresion这个时间去执行excute方法。
你也可以在自己的其他业务里面直接调用 scheduleJobTest() 或者delete删除方法。
另外:我这实现了一个LazyInitBean接口,让容器初始化的时候就去执行。写的有点乱,反正就这几个类,和bean,和数据库表,对应上就行了。



package com.surekam.collie.scene.finalTest;

import com.surekam.collie.scene.bean.HistoryPO;
import com.surekam.collie.scene.bean.ScheduleJob;
import com.surekam.collie.scene.service.SceneService;
import com.surekam.platform.core.container.ApplicationContext;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

import java.util.Date;

public class QuartzJobFactory implements Job {
    private static final Log log = LogFactory.getLog(QuartzJobFactory.class);
    private SceneService sceneService = (SceneService) ApplicationContext
            .getInstance().getBizComponent("sceneService");


    /**
     * 最终执行往数据库中加场景id和时间
     * @param context
     * @throws JobExecutionException
     */
    @Override
    synchronized public void execute(JobExecutionContext context) throws JobExecutionException {
        ScheduleJob scheduleJob = (ScheduleJob) context.getMergedJobDataMap().get("scheduleJob");
        String sceneId = scheduleJob.getSceneId();
        Date date = new Date();
        String cronExpression = scheduleJob.getCronExpression();
        HistoryPO historyPO = new HistoryPO();
        historyPO.setScene_id(sceneId);
        historyPO.setTime_step(cronExpression);
        historyPO.setScene_time(date);
//        sceneService.saveOrUpdateHistory(historyPO);
        // TODO: 2017/8/8  注掉
//        log.info("任务成功运行");
//        log.info("任务名称 = [" + scheduleJob.getJobName() + "]");
    }
}