一、导入依赖
<!--任务调度依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-quartz</artifactId>
</dependency>
二、具体实现
现在继承QuartzJobBean类一定要实现protected void executeInternal(JobExecutionContext jobExecutionContext) 方法了,要在该方法里面写自己要调用的接口。
import com.group.oayouth.entity.Message;
import com.group.oayouth.service.IMessageService;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.quartz.QuartzJobBean;
import java.time.LocalDateTime;
/**
* 功能描述(Description):定时调用的方法
*/
public class jobTest extends QuartzJobBean {
@Autowired
private IMessageService messageService;
@Override
protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException {
Message message=new Message();
message.setCreateTime(LocalDateTime.now());
message.setMsgContent("定时器测试");
message.setReceiverId((long) 2);
messageService.createMessage(message);
}
}
import com.group.oayouth.schedule.job.jobTest;
import org.quartz.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* 功能描述(Description):调度配置
*/
@Configuration
public class QuartzConfig {
/**
* 定时任务
*/
@Bean
public JobDetail timeOutDetail() {
return JobBuilder.newJob(jobTest.class)
.withIdentity("jobTest")
.storeDurably()
.build();
}
/**
* 触发器
*/
@Bean
public Trigger timeOutTrigger() {
//每隔3秒执行一次
CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule("*/3 * * * * ?");
//创建触发器
return TriggerBuilder.newTrigger()
.forJob(timeOutDetail())
.withIdentity("timeOutTrigger")
.startNow()
.withSchedule(cronScheduleBuilder)
.build();
}
}
你要是不需要定时调用多个接口,业务上很少用到还能写成更简单,直接在定时调用的方法上加@Scheduled
注解,如下图的@Scheduled(cron = "0/10 * * * * *")