因为springboot在国内还很少使用,今天刚好碰到要做,就把代码贴出来。
首先导入maven依赖:
请注意不要重复添加依赖,以免报错。
新建quartz.properties,此文件为链接数据库的核心配置文件
抛出错误:check the manual that corresponds to your MySQL server version for the right syntax to use near
'(UPDLOCK,ROWLOCK) WHERE SCHED_NAME = 'startQuertz' AND LOCK_NAME = 'TRIGGER_ACCE' at line 1
这个错误也就是sql语法错误,可能是驱动的问题,具体也不清楚 因此 我换成了 org.quartz.impl.jdbcjobstore.StdJDBCDelegate 如果没有问题的可以继续使用
org.quartz.impl.jdbcjobstore.MSSQLDelegate
新建application.properties(如果已存在,无需再建,此配置文件是springboot核心,在此配置数据库连接信息,这就不用废话了)
然后再新建quartz.xml配置定时任务
接下来新建com.test.quartz.job.DetailQuartzJobBean类 这个类的作用主要用于加载类和方法,用到了java的放射
最后我们把定时任务代码贴出来:
至此,大功告成!
首先导入maven依赖:
<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz</artifactId>
<version>2.2.1</version>
</dependency>
<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz-jobs</artifactId>
<version>2.2.1</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>4.2.7.RELEASE</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.38</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.11</version>
</dependency>
请注意不要重复添加依赖,以免报错。
新建quartz.properties,此文件为链接数据库的核心配置文件
org.quartz.scheduler.instanceName = quartzScheduler
org.quartz.scheduler.instanceId = AUTO
org.quartz.jobStore.class = org.quartz.impl.jdbcjobstore.JobStoreTX
org.quartz.jobStore.driverDelegateClass = org.quartz.impl.jdbcjobstore.StdJDBCDelegate
org.quartz.jobStore.tablePrefix = QRTZ_
org.quartz.jobStore.isClustered = true
org.quartz.jobStore.useProperties = false
org.quartz.jobStore.clusterCheckinInterval = 20000
org.quartz.threadPool.class = org.quartz.simpl.SimpleThreadPool
org.quartz.threadPool.threadCount = 10
org.quartz.threadPool.threadPriority = 5
org.quartz.threadPool.threadsInheritContextClassLoaderOfInitializingThread = true
此文件的driverDelegateClass的值有的伙伴可能使用org.quartz.impl.jdbcjobstore.MSSQLDelegate 但是我的是错误的,
抛出错误:check the manual that corresponds to your MySQL server version for the right syntax to use near
'(UPDLOCK,ROWLOCK) WHERE SCHED_NAME = 'startQuertz' AND LOCK_NAME = 'TRIGGER_ACCE' at line 1
这个错误也就是sql语法错误,可能是驱动的问题,具体也不清楚 因此 我换成了 org.quartz.impl.jdbcjobstore.StdJDBCDelegate 如果没有问题的可以继续使用
org.quartz.impl.jdbcjobstore.MSSQLDelegate
新建application.properties(如果已存在,无需再建,此配置文件是springboot核心,在此配置数据库连接信息,这就不用废话了)
#########mysql#########
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/test_job?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true
spring.datasource.username=test
spring.datasource.password=test
spring.datasource.initialSize=5
spring.datasource.minIdle=5
spring.datasource.maxActive=20
spring.datasource.maxWait=60000
spring.datasource.timeBetweenEvictionRunsMillis=3600000
spring.datasource.minEvictableIdleTimeMillis=18000000
spring.datasource.validationQuery=SELECT 1 FROM DUAL
spring.datasource.testWhileIdle=true
spring.datasource.testOnBorrow=true
spring.datasource.testOnReturn=true
spring.datasource.poolPreparedStatements=true
spring.datasource.maxPoolPreparedStatementPerConnectionSize=20
spring.datasource.filters=stat,wall,log4j
spring.datasource.connectionProperties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
然后再新建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:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<bean id="testJobDetail" class="org.springframework.scheduling.quartz.JobDetailFactoryBean">
<!-- durability 表示任务完成之后是否依然保留到数据库,默认false -->
<property name="durability" value="true" />
<property name="requestsRecovery" value="true" />
<property name="jobClass">
<value>
com.test.quartz.job.DetailQuartzJobBean
</value>
</property>
<property name="jobDataAsMap">
<map>
<entry key="targetObject" value="testScheduleTask" />
<entry key="targetMethod" value="sayHello" />
<!-- 是否允许任务并发执行。当值为false时,表示必须等到前一个线程处理完毕后才再启一个新的线程 -->
<entry key="concurrent" value="false" />
</map>
</property>
</bean>
<bean id="testJobTrigger"
class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">
<property name="jobDetail">
<ref bean="testJobDetail" />
</property>
<property name="cronExpression">
<value>0/5 * * * * ?</value><!--每5秒钟执行一次 -->
</property>
</bean>
<bean id="startQuertz" lazy-init="false" autowire="no"
class="org.springframework.scheduling.quartz.SchedulerFactoryBean"
destroy-method="destroy">
<!--QuartzScheduler 启动时更新己存在的Job,这样就不用每次修改targetObject后删除qrtz_job_details表对应记录了 -->
<property name="overwriteExistingJobs" value="true" />
<property name="startupDelay" value="2" />
<property name="autoStartup" value="true" />
<property name="triggers">
<list>
<ref bean="testJobTrigger" />
</list>
</property>
<property name="dataSource" ref="dataSource" />
<property name="applicationContextSchedulerContextKey" value="applicationContext" />
<property name="configLocation" value="classpath:quartz.properties" />
</bean>
</beans>
接下来新建com.test.quartz.job.DetailQuartzJobBean类 这个类的作用主要用于加载类和方法,用到了java的放射
public class DetailQuartzJobBean extends QuartzJobBean {
protected final Log logger = LogFactory.getLog(getClass());
private String targetObject;
private String targetMethod;
private ApplicationContext ctx;
@Override
protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
try {
Object otargetObject = ctx.getBean(targetObject);
Method m = null;
try {
m = otargetObject.getClass().getMethod(targetMethod, new Class[] { JobExecutionContext.class });
m.invoke(otargetObject, new Object[] { context });
} catch (SecurityException e) {
logger.error(e);
} catch (NoSuchMethodException e) {
logger.error(e);
}
} catch (Exception e) {
throw new JobExecutionException(e);
}
}
public void setApplicationContext(ApplicationContext applicationContext) {
this.ctx = applicationContext;
}
public void setTargetObject(String targetObject) {
this.targetObject = targetObject;
}
public void setTargetMethod(String targetMethod) {
this.targetMethod = targetMethod;
}
}
最后我们把定时任务代码贴出来:
import org.quartz.JobExecutionContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.stereotype.Component;
@Configuration
@Component("testScheduleTask")
@EnableScheduling
public class ScheduleTask {
public void sayHello(JobExecutionContext context){
System.out.println("123456789");
}
}
至此,大功告成!