一、引入 jar 。
<!-- quartz 定时任务调度 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
</dependency>
<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>
二 、实现方式 一 。
1. 定义好定时任务的业务内容:
package gentle.test;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import java.util.Date;
/**
* @author silence
* @date 2018/7/17 11:37
*/
@Service("show")
public class Show implements Job {
private static Logger _log = LoggerFactory.getLogger(Show.class);
@Override
public void execute(JobExecutionContext arg0) throws JobExecutionException {
_log.info("\n\n-------------------------------\n " +
"It is running and the time is : " + new Date()+
"\n-------------------------------\n");
}
}
2. 声明定时任务,并关联业务实现类 。在 JobDetail jb = JobBuilder.newJob(Show.class) 中关联业务类 。
package gentle.test;
import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import java.util.Date;
/**
* @author silence
* @date 2018/7/17 11:36
*/
@Service("schedulerTest")
public class SchedulerTest {
private static Logger _log = LoggerFactory.getLogger(Scheduler.class);
public static void main(String[] args) {
try {
//1.创建Scheduler的工厂
SchedulerFactory sf = new StdSchedulerFactory();
//2.从工厂中获取调度器实例
Scheduler scheduler = sf.getScheduler();
//3.创建JobDetail
JobDetail jb = JobBuilder.newJob(Show.class) // Show 为一个job,是要执行的一个任务。
.withDescription("这是我的测试定时任务。") //job的描述
.withIdentity("jy2Job", "jy2Group") //job 的name和group
.build();
//任务运行的时间,SimpleSchedle类型触发器有效
long time = System.currentTimeMillis() + 3 * 1000L; // 3秒后启动任务
Date statTime = new Date(time);
//4.创建Trigger
//使用SimpleScheduleBuilder或者CronScheduleBuilder
Trigger t = TriggerBuilder.newTrigger()
.withDescription("")
.withIdentity("jyTrigger", "jyTriggerGroup")
//.withSchedule(SimpleScheduleBuilder.simpleSchedule())
.startAt(statTime) //默认当前时间启动 ,也可以写为:.startNow();
.withSchedule(CronScheduleBuilder.cronSchedule("0/2 * * * * ?")) //两秒执行一次
.build();
//5.注册任务和定时器
scheduler.scheduleJob(jb, t);
//6.启动 调度器
scheduler.start();
_log.info("启动时间 : " + new Date());
} catch (Exception e) {
_log.info("定时任务出现异常 : " + e);
}
}
}
3. 运行成功:
实现方式 二 。
1. 定义好定时任务的业务内容:
package gentle.test;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import java.util.Date;
/**
* @author silence
* @date 2018/7/17 11:37
*/
@Service("show")
public class Show implements Job {
private static Logger _log = LoggerFactory.getLogger(Show.class);
@Override
public void execute(JobExecutionContext arg0) throws JobExecutionException {
_log.info("\n\n-------------------------------\n " +
"It is running and the time is : " + new Date()+
"\n-------------------------------\n");
}
}
2. 定义好定时任务的触发类,调用业务类中的实现 。
package gentle.test;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
public class UserSyncTask {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
@Resource
Show show;
public void cronDepartmentsAndUsersJob() {
logger.info("\n\n 定时--开始,当前时间: " + dateFormat().format(new Date()));
try {
show.execute(null);
} catch (JobExecutionException e) {
e.printStackTrace();
}
logger.info("\n\n 定时--结束,当前时间:" + dateFormat().format(new Date()));
}
private SimpleDateFormat dateFormat() {
return new SimpleDateFormat("HH:mm:ss");
}
}
3. 配置文件中 配置触发类和任务执行频率 。
<?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:util="http://www.springframework.org/schema/util"
xmlns:task="http://www.springframework.org/schema/task"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task.xsd">
<!--定时任务触发类-->
<bean id="userSyncTask" class="gentle.test.UserSyncTask"></bean>
<!--执行频率-->
<task:scheduled-tasks>
<!--每 2 秒执行一次-->
<task:scheduled ref="userSyncTask" method="cronDepartmentsAndUsersJob" cron="0/2 * * * * ?" />
</task:scheduled-tasks>
</beans>
4. 运行成功: