Springboot使用Quartz定时任务

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();
    }
}
原文地址:https://www.cnblogs.com/shoose/p/12930649.html