scheduler定时调度系统是大多行业项目都需要的,传统的spring-job模式,个人感觉已经out了,因为存在很多的问题,特别是定时调度的追加、修改、删除等,需要修改xml,xml的配置生效无非是热部署灰度发布方案或者直接停止、重启服务器,完全不能做到自动启动、修复方式。
提醒:可以对应用进行集群部署,在对定时调度配置时可以使用集群方式或者单边配置应用方式,今天讲解的是使用spring4+scheduler实现定时调度,闲话少说,直接把步骤记录下来:
1. 在项目的pom.xml文件中引入quartz的jar包,如下:
- <!-- quartz定时调度 -->
- lt;dependency>
- <groupId>org.quartz-scheduler</groupId>
- <artifactId>quartz</artifactId>
- <version>1.8.5</version>
- lt;/dependency>
2. 定义quartz的配置文件spring-context-quartz.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"
- xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="
- http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
- http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd"
- default-lazy-init="false">
- <!-- 调度器 -->
- <bean name="scheduler" class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
- <!-- 通过applicationContextSchedulerContextKey属性配置spring上下文 -->
- <property name="applicationContextSchedulerContextKey" value="applicationContext" />
- </bean>
- <!--加载数据库任务-->
- <bean id="jobService" class="com.ml.honghu.job.service.JobService" init-method="loadJob" />
- </beans>
3. 在项目的web.xml文件中引入spring-context-quartz.xml配置文件
- classpath*:spring-context-quartz.xml
4. 定义job实体对象
- public class Job{
- private static final long serialVersionUID = 1L;
- /**
- * 任务执行周期cron表达式
- */
- public static int EXECYCLE_CRON = 2;
- /**
- * 任务执行周期自定义
- */
- public static int EXECYCLE_DEFINE = 1;
- /**
- * 执行周期-分钟
- */
- public static int EXECYCLE_MINUTE = 1;
- /**
- * 执行周期-小时
- */
- public static int EXECYCLE_HOUR = 2;
- /**
- * 执行周期-日
- */
- public static int EXECYCLE_DAY = 3;
- /**
- * 执行周期-月
- */
- public static int EXECYCLE_WEEK = 4;
- /**
- * 执行周期-月
- */
- public static int EXECYCLE_MONTH = 5;
- private String jobType; // 任务类型(1首页静态化、2栏目页静态化、3内容页静态化、4采集、5分发)
- private String jobName; // 任务名称
- private String jobClass; // 任务类
- private String execycle; // 执行周期分类(1非表达式 2 cron表达式)