SpringBoot2.0+整合Quartz 定时任务

SpringBoot2.X 与定时任务

定时器选择

有基于Quartz的定时器 更全面 有Spring自带的定时 (单线程)基于注解@Scheduled

(1)基于注解@Scheduled

优点:简单,好用,没有复杂场景直接使用他,除了支持灵活的参数表达式cron之外,还支持简单的延时操作,例如 fixedDelay ,fixedRate 填写相应的毫秒数即可。

缺点:默认为单线程,开启多个任务时,任务的执行时机会受上一个任务执行时间的影响。 可以通过@EnableAsync注解开启多线程

首先在SpringBoot启动类加上一个注解

单线程用法

@EnableScheduling
@Component
@EnableScheduling   // 2.开启定时任务
public class SaticScheduleTask {
    //3.添加定时任务
    @Scheduled(cron = "0/5 * * * * ?")
    //或直接指定时间间隔,例如:5秒
    //@Scheduled(fixedRate=5000)
    private void configureTasks() {
        System.err.println("执行静态定时任务时间: " + LocalDateTime.now());
    }
}

多线程用法

@Component     //无实际意义 (交给Spring管理   可不用)
@EnableScheduling   // 1.开启定时任务
@EnableAsync        // 2.开启多线程 
public class MultithreadScheduleTask {

        @Async  //多线程
        @Scheduled(fixedDelay = 1000)  //间隔1秒
        public void first() throws InterruptedException {
            System.out.println("第一个定时任务开始 : " + LocalDateTime.now().toLocalTime() + "线程 : " + Thread.currentThread().getName());
            System.out.println();
            Thread.sleep(1000 * 10);
        }

        @Async  //多线程
        @Scheduled(fixedDelay = 2000)
        public void second() {
            System.out.println("第二个定时任务开始 : " + LocalDateTime.now().toLocalTime() + "线程 : " + Thread.currentThread().getName());
            System.out.println();
        }
    }

(2)Quartz定时器

优点:多线程定时任务 不会因为上一个定时任务未执行完毕而造成定时等待

导包

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-quartz</artifactId>
		</dependency>

编写任务类 继承 QuartzJobBean 覆写父类 executeInternal方法 ,其中 在executeInternal中编写要定时执行的业务逻辑即可

import cn.leilei.mapper.RealEseateMapper;
import cn.leilei.service.IRealEseateService;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.quartz.QuartzJobBean;
import org.springframework.stereotype.Component;

import java.util.Date;
@Component
public class TestQuartz extends QuartzJobBean {

    @Autowired
    private IRealEseateService realEseateService;//测试定时执行  与数据库交互
    /** * 执行定时任务 * * @param jobExecutionContext * @throws JobExecutionException */
    @Override
    protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        realEseateService.list().forEach(e-> System.out.println(e));
        System.out.println("ttt" + new Date());
    }
}

编写定时任务配置类

两种定时 一种是是触发时间 ,使用cron表达式 ,一直是触发时间 设置触发间隔时间 默认 单位 秒

import org.quartz.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class QuartzConfig {
    @Bean
    public JobDetail teatQuartzDetail() {
        return JobBuilder.newJob(TestQuartz.class).withIdentity("testQuartz").storeDurably().build();
    }

/*    @Bean
    public Trigger testQuartzTrigger() {
        //设置时间周期单位秒 每隔两秒实行一次
        SimpleScheduleBuilder scheduleBuilder = SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(20).repeatForever();
        return TriggerBuilder.newTrigger().forJob(teatQuartzDetail()) .withIdentity("testQuartz") .withSchedule(scheduleBuilder) .build();

    }*/
    //cron 表达式
    @Bean
    public Trigger uploadTaskTrigger() {
        CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule("*/5 * * * * ?");
        return TriggerBuilder.newTrigger().forJob(teatQuartzDetail())
                .withIdentity("testQuartz")
                .withSchedule(scheduleBuilder)
                .build();
    }
}

至此 ,SpringBoot整合定时任务就完成了,当然这也只是一个简单的整合,没有特别复杂的业务逻辑 已经可以达到了,需要更多的整合可以自行百度 Quartz定时工具类

小提示:

Cron表达式参数分别表示:

  • 秒(0~59) 例如0/5表示每5秒
  • 分(0~59)
  • 时(0~23)
  • 日(0~31)的某天,需计算
  • 月(0~11)
  • 周几( 可填1-7 或 SUN/MON/TUE/WED/THU/FRI/SAT)
发布了31 篇原创文章 · 获赞 23 · 访问量 3804

猜你喜欢

转载自blog.csdn.net/leilei1366615/article/details/102665484