1、添加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-quartz</artifactId>
</dependency>
<dependency>
2、继承 QuartzJobBean 类,实现具体的业务逻辑
package com.example.demo.job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.scheduling.quartz.QuartzJobBean;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* @author lyd
* @Description:
* @date 17:10
*/
public class HiJob extends QuartzJobBean {
@Override
protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException {
// 获取jobDetail中传递的参数
String userNamge = (String) jobExecutionContext.getJobDetail().getJobDataMap().get("用户名");
String url = (String) jobExecutionContext.getJobDetail().getJobDataMap().get("url");
String remark = (String) jobExecutionContext.getJobDetail().getJobDataMap().get("问候语");
Date date = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-mm-dd hh:mm:ss");
System.out.println();
System.out.println("用户名:" + userNamge);
System.out.println("地址:" + url);
System.out.println("问候语:" + remark);
System.out.println("时间:" + dateFormat.format(date));
System.out.println();
}
}
3、配置定时任务
package com.example.demo.config;
import com.example.demo.job.HiJob;
import org.quartz.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* 配置
*
* @author lyd
* @Description:
* @date 17:29
*/
@Configuration
public class QuartzConfig {
/**
* 工作的组名
*/
private final static String JOB_GROUP_NAME = "LIU_JOB_GROUP_NAME";
/**
* 触发组名称
*/
private final static String TRIGGER_GROUP_NAME = "LIU_TRIGGER_GROUP_NAME";
/**
* 任务详情
* 同步用户的工作细节
*
* @return {@link JobDetail}
*/
@Bean
public JobDetail syncUserJobDetail() {
JobDetail jobDetail = JobBuilder
.newJob(HiJob.class)
.withIdentity("syncUserJobDetail", JOB_GROUP_NAME)
.usingJobData("用户名", "这是我的用户名")
.usingJobData("url", "www.baidu.hhahaahah")
.usingJobData("问候语", "你好,啦啦啦啊")
.storeDurably()//持久化,即使没有Trigger关联时也不需要删除该jobdetail
.build();
return jobDetail;
}
/**
* 同步userjob触发
* 同步用户信息触发器
*
* @return {@link Trigger}
*/
@Bean
public Trigger syncUserjobTrigger() {
// 每5秒执行一次
CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule("0/5 * * * * ?");
Trigger trigger = TriggerBuilder.newTrigger()
.forJob(syncUserJobDetail())//关联上面那个JobDetail
.withIdentity("我是Trigger的名字", TRIGGER_GROUP_NAME)
.withSchedule(cronScheduleBuilder)
.build();
return trigger;
}
}