1、在pom.xml文件中配置引入jar包
<!--配置quartz,定時任務--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-quartz</artifactId> </dependency>
2、創建CheckDevStatusQuartz類
import com.well.driving.service.AlarmService; import org.quartz.JobExecutionContext; import org.quartz.JobExecutionException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.scheduling.quartz.QuartzJobBean; import java.text.SimpleDateFormat; import java.util.Date; public class CheckDevStatusQuartz extends QuartzJobBean { @Autowired private XxxService xxxService; /** * 執行定時任務 * * @param jobExecutionContext * @throws JobExecutionException */ @Override protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException {
//此處為你要運行的任務具體接口 xxxService.checkDeviceStatus(); System.out.println("Check device status" + "=========" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())); } }
3、創建QuartzConfig類
import com.well.driving.quartz.CheckDevStatusQuartz; import org.quartz.*; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class QuartzConfig { @Bean public JobDetail checkDevStatusDetail() { return JobBuilder.newJob(CheckDevStatusQuartz.class).withIdentity("checkDevStatusQuartz").storeDurably().build(); } @Bean public Trigger testQuartzTrigger() { SimpleScheduleBuilder scheduleBuilder = SimpleScheduleBuilder.simpleSchedule() .withIntervalInSeconds(120) //設置時間周期單位秒,目前設置為2分鍾一次 .repeatForever(); return TriggerBuilder.newTrigger().forJob(checkDevStatusDetail()) .withIdentity("checkDevStatusQuartz") .withSchedule(scheduleBuilder) .build(); } }