java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > Springboot定时任务

Springboot集成Quartz实现定时任务代码实例

作者:CD4356

这篇文章主要介绍了Springboot集成Quartz实现定时任务代码实例,任务是有可能并发执行的,若Scheduler直接使用Job,就会存在对同一个Job实例并发访问的问题,而JobDetail & Job方式,Scheduler都会根据JobDetail创建一个新的Job实例,这样就可以规避并发访问问题

Springboot集成Quartz实现定时任务代码实例

Quartz是一款功能强大的任务调度器,Quartz有两个比较核心的组件:Job 和 Trigger。

Quartz的三个基本要素

Spring Boot自带定时任务,默认是单线程

1. 使用spring boot自带定时任务无需添加相关依赖包

2. 在启动类上添加 @EnableScheduling 注解

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
@SpringBootApplication
@EnableScheduling
public class O2o2Application {
    public static void main(String[] args) {
        SpringApplication.run(O2o2Application.class, args);
        System.out.println("项目启动成功!");
    }
}

3. 在方法上标注 @Scheduled 注解,指定该方法作为定时任务运行的方法。并通过cron属性设置cron表达式,来指定定时任务的执行时间

import com.cd.o2o2.dao.ProductSellDailyDao;
import com.cd.o2o2.service.ProductSellDailyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import java.text.SimpleDateFormat;
import java.util.Date;
@Service("productSellDailyService")
public class ProductSellDailyServiceImpl implements ProductSellDailyService {
	@Override
    @Scheduled(cron = "0/2 * * * * ?") //定时任务运行的方法
    public void demo1() {
        SimpleDateFormat dataFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println(dataFormat.format(new Date()) + "  Quartz Running!");
    }
	@Override
    @Scheduled(cron = "0/5 * * * * ?") //定时任务运行的方法
    public void demo2() {
        SimpleDateFormat dataFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println("\n当前执行时间: " + dataFormat.format(new Date()) + "\n");
    }
}

启动SpringBoot,查看控制台打印信息! demo1()每2秒定时运行一次,demo2()每5秒定时运行一次 cd4356

如果不想使用Spring Boot自带的定时任务,则需要添加quartz相关依赖包

pom.xml

<!--定时组件-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-quartz</artifactId>
</dependency>

Quartz配置类(Job的定义有两种方式,分别为JobDetailFactoryBean和MethodInvokingJobDetailFactoryBean,下面使用MethodInvokingJobDetailFactoryBean类来定义job)

package com.cd.o2o2.config.quartz;
import com.cd.o2o2.service.ProductSellDailyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.quartz.CronTriggerFactoryBean;
import org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
@Configuration //标注@Configuration的类,相当于一个xml配置文件
public class QuartzConfiguration {
    @Autowired
    private ProductSellDailyService productSellDailyService;
    @Autowired
    private MethodInvokingJobDetailFactoryBean jobDetailFactory;
    @Autowired
    private CronTriggerFactoryBean cronTriggerFactory;
    /**
     * 配置jobDetail作业类
     * @return
     */
    @Bean(name = "jobDetailFactory") //标注@Bean后表明返回对象会被当做一个Bean注册到Spring IoC容器
    public MethodInvokingJobDetailFactoryBean createJobDetail(){
        MethodInvokingJobDetailFactoryBean jobDetailFactoryBean = new MethodInvokingJobDetailFactoryBean();
        //指定任务名称
        jobDetailFactoryBean.setName("product_sell_daily_job");
        //指定组名称
        jobDetailFactoryBean.setGroup("job_product_sell_daily_group");
        /*
          对于同一个JobDetail,当指定多个trigger时,很可能第一个job完成之前,第二个job就开始了
          指定concurrent属性为false,多个job就会串行执行,而不会并发执行,即第一个job完成前,第二个job不会开启
         */
        jobDetailFactoryBean.setConcurrent(false);
        //指定具体的job任务类
        jobDetailFactoryBean.setTargetObject(productSellDailyService);
        //指定运行任务的方法
        jobDetailFactoryBean.setTargetMethod("dailyCalculate");
        return jobDetailFactoryBean;
    }
    /**
     * 配置cronTrigger触发器(作业调度的方式)
     * @return
     */
    @Bean(name = "cronTriggerFactory")
    public CronTriggerFactoryBean createProductSellDailyTrigger(){
        CronTriggerFactoryBean triggerFactory = new CronTriggerFactoryBean();
        //指定trigger的名称
        triggerFactory.setName("product_sell_daily_trigger");
        //指定trigger的组名
        triggerFactory.setGroup("job_product_sell_daily_group");
        //指定trigger绑定的job
        triggerFactory.setJobDetail(jobDetailFactory.getObject());
        //设置cron表达式,每天凌晨定时运行(通过在线Cron表达式生成器来生成)
        triggerFactory.setCronExpression("0/2 * * * * ?");
        return triggerFactory;
    }
    /**
     * 配置scheduler调度工厂
     * @return
     */
    @Bean
    public SchedulerFactoryBean createScheduler(){
        SchedulerFactoryBean schedulerFactory = new SchedulerFactoryBean();
        //绑定cronTrigger
        schedulerFactory.setTriggers(cronTriggerFactory.getObject());
        return schedulerFactory;
    }
}

dailyCalculate()方法,是定时任务运行的方法

package com.cd.o2o2.service.impl;
import com.cd.o2o2.service.ProductSellDailyService;
import org.springframework.stereotype.Service;
import java.util.Date;
@Service("productSellDailyService")
public class ProductSellDailyServiceImpl implements ProductSellDailyService {
    /**
     * 定时任务运行的方法
     */
    @Override
    public void dailyCalculate() {
        System.out.println(new Date()+": Quartz Running!");
    }
}

启动SpringBoot,查看控制台打印信息!dailyCalculate()方法每2秒定时运行一次

cd4356

Cron表达式示例

cd4356

到此这篇关于Springboot集成Quartz实现定时任务代码实例的文章就介绍到这了,更多相关Springboot定时任务内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文