目录:
- 依赖
- 创建任务类
- 配置类
参考/来源:
依赖
<!-- SpringBoot 整合 Quartz 定时任务 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-quartz</artifactId>
<version>2.3.5.RELEASE</version>
</dependency>
创建任务类
package com.pjb.job;
import org.quartz.JobExecutionContext;
import org.springframework.scheduling.quartz.QuartzJobBean;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* 同步用户信息Job
* @author pan_junbiao
**/
public class SyncUserJob extends QuartzJobBean
{
@Override
protected void executeInternal(JobExecutionContext jobExecutionContext)
{
//获取JobDetail中传递的参数
String userName = (String) jobExecutionContext.getJobDetail().getJobDataMap().get("userName");
String blogUrl = (String) jobExecutionContext.getJobDetail().getJobDataMap().get("blogUrl");
String blogRemark = (String) jobExecutionContext.getJobDetail().getJobDataMap().get("blogRemark");
//获取当前时间
Date date = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//打印信息
System.out.println("用户名称:" + userName);
System.out.println("博客地址:" + blogUrl);
System.out.println("博客信息:" + blogRemark);
System.out.println("当前时间:" + dateFormat.format(date));
System.out.println("----------------------------------------");
}
}
配置类
package com.pjb.config;
import com.pjb.job.SyncUserJob;
import org.quartz.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* Quartz定时任务配置类
* @author pan_junbiao
**/
@Configuration
public class QuartzConfig
{
private static String JOB_GROUP_NAME = "PJB_JOBGROUP_NAME";
private static String TRIGGER_GROUP_NAME = "PJB_TRIGGERGROUP_NAME";
/**
* 定时任务1:
* 同步用户信息Job(任务详情)
*/
@Bean
public JobDetail syncUserJobDetail()
{
JobDetail jobDetail = JobBuilder.newJob(SyncUserJob.class)
.withIdentity("syncUserJobDetail",JOB_GROUP_NAME)
.usingJobData("userName", "pan_junbiao的博客") //设置参数(键值对)
.usingJobData("blogUrl","https://blog.csdn.net/pan_junbiao")
.usingJobData("blogRemark","您好,欢迎访问 pan_junbiao的博客")
.storeDurably() //即使没有Trigger关联时,也不需要删除该JobDetail
.build();
return jobDetail;
}
/**
* 定时任务1:
* 同步用户信息Job(触发器)
*/
@Bean
public Trigger syncUserJobTrigger()
{
//每隔5秒执行一次
CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule("0/5 * * * * ?");
//创建触发器
Trigger trigger = TriggerBuilder.newTrigger()
.forJob(syncUserJobDetail())//关联上述的JobDetail
.withIdentity("syncUserJobTrigger",TRIGGER_GROUP_NAME)//给Trigger起个名字
.withSchedule(cronScheduleBuilder)
.build();
return trigger;
}
}