栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java > SpringBoot

SpringBoot整合实现定时任务

SpringBoot 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

SpringBoot整合实现定时任务

一、定时任务实现的几种方式

1. Timer:线程调度任务以供将来在后台线程中执行的功能。 任务可以安排一次执行,或定期重复执行。Timer是java自带的java.util.Timer类,这个类允许你调度一个java.util.TimerTask任务。使用这种方式可以让你的程序按照某一个频度执行,但不能在指定时间运行。一般用的较少。

API文档:http://www.matools.com/file/manual/jdk_api_1.8_google/index.html?overview-summary.html


2. ScheduledExecutorService:也jdk自带的一个类,位于java.util.concurrent包下;它是基于线程池设计的定时任务类,每个调度任务都会分配到线程池中的一个线程去执行,也就是说,任务是并发执行,互不影响。

API文档:http://www.matools.com/file/manual/jdk_api_1.8_google/index.html?overview-summary.html


3. Spring Task:Spring3.0以后自带的task,可以将它看成一个轻量级的Quartz,而且使用起来比Quartz简单许多。

官方文档:https://spring.io/guides/gs/scheduling-tasks/


4. Quartz:是一个由 Java 编写的开源作业调度框架,为在 Java 应用程序中进行作业调度提供了简单却强大的机制。这是一个功能比较强大的的调度器,可以让你的程序在指定时间执行,也可以按照某一个频度执行,配置起来稍显复杂。它允许程序开发人员根据时间的间隔来调度作业,并且实现了作业和触发器的多对多的关系,还能把多个作业与不同的触发器关联。官网:http://www.quartz-scheduler.org/


5. 第三方定时任务调度工具,比如:xxl-job(https://gitee.com/xuxueli0323/xxl-job)

二、SpringBoot整合实现几种定时任务

1. 创建SpringBoot项目,引入相关的jar包到pom.xml文件


    org.springframework.boot
    spring-boot-starter-quartz


    org.springframework.boot
    spring-boot-starter-web



    com.alibaba
    fastjson
    1.2.62

其他jar包都是自带的,不用导入了

2. 创建的项目结构如下:

3. 代码实现

(1)配置类:

AsyncConfig.java ——异步任务配置类

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;


@Configuration   //表明该类是一个配置类
@EnableAsync //开启异步事件的支持
public class AsyncConfig {

    
    private int corePoolSize = 10;
    private int maxPoolSize = 200;
    private int queueCapacity = 10;

    @Bean
    public Executor taskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(corePoolSize);
        executor.setMaxPoolSize(maxPoolSize);
        executor.setQueueCapacity(queueCapacity);
        executor.initialize();
        return executor;
    }
}

QuartzConfig.java——Quartz调度任务配置类

import com.lhf.springboot.quartz.QuartzTest;
import com.lhf.springboot.quartz.QuartzTest1;
import org.quartz.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;


@Configuration
public class QuartzConfig {

    @Bean
    public JobDetail quartzDetail(){
        return JobBuilder.newJob(QuartzTest.class).withIdentity("quartzTest").storeDurably().build();

    }

    @Bean
    public Trigger quartzTrigger(){
        SimpleScheduleBuilder scheduleBuilder = SimpleScheduleBuilder.simpleSchedule()
                .withIntervalInSeconds(15)  //设置时间周期单位秒
                .repeatForever();
        return TriggerBuilder.newTrigger().forJob(quartzDetail())
                .withIdentity("quartzTestJob")
                .withSchedule(scheduleBuilder)
                .build();
    }

    

    @Bean
    public JobDetail interviewPlansJobDetail(){
        return JobBuilder.newJob(QuartzTest1.class)//PrintTimeJob我们的业务类
                .withIdentity("quartzTest1")//可以给该JobDetail起一个id
                //每个JobDetail内都有一个Map,包含了关联到这个Job的数据,在Job类中可以通过context获取
                .usingJobData("msg1", "quartzTest1")//关联键值对
                .storeDurably()//即使没有Trigger关联时,也不需要删除该JobDetail
                .build();
    }
    @Bean
    public Trigger interviewPlansJobTrigger() {
        CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule("0 0/3 * * * ? ");   // 0 0 0/1 * * ?
        return TriggerBuilder.newTrigger()
                .forJob(interviewPlansJobDetail())//关联上述的JobDetail
                .withIdentity("quartzTestJob1")//给Trigger起个名字
                .withSchedule(cronScheduleBuilder)
                .build();
    }
}

(2)quartz实现定时任务

QuartzTest.java——quartz定时任务1

import com.lhf.springboot.util.RandomUtils;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.scheduling.quartz.QuartzJobBean;


public class QuartzTest extends QuartzJobBean {
    //执行定时任务
    @Override
    protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        System.out.println("quartz定时任务1: " + RandomUtils.getRandomString());
    }
}

QuartzTest1.java——quartz定时任务2

import com.lhf.springboot.util.RandomUtils;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.scheduling.quartz.QuartzJobBean;


public class QuartzTest1 extends QuartzJobBean {

    @Override
    protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        System.out.println("quartz定时任务2: " + RandomUtils.getRandomNum(4) + "-->" + RandomUtils.getRandomString());
    }
}

(3)ScheduledExecutorService实现定时任务

ScheduledExecutorServiceDemo.java

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.Date;


public class ScheduledExecutorServiceDemo {

    public void scheduledJob(){

        ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();

        //参数:1.任务名称 2. 首次执行的延时时间 3. 任务执行间隔 4. 间隔时间单位
        service.scheduleAtFixedRate(()->System.out.println("ScheduledExecutorService Job : " + new Date()), 0, 4, TimeUnit.SECONDS);

    }
}

(4)Spring Task实现定时任务

AsyncTask.java——开启异步任务

import com.lhf.springboot.util.RandomUtils;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;


@Async  //开启异步任务类,类中的每个方法都是定时任务,该注解可以加到类和方法上
@Component
public class AsyncTask {

    //@Async
    @Scheduled(cron = "0/7 * * * * * ")
    public void task1(){
        System.out.println("异步任务1: " + System.currentTimeMillis());
    }

    //@Async
    @Scheduled(cron = "0/9 * * * * * ")
    public void task2(){
        System.out.println("异步任务2:" + RandomUtils.getRandomString());
    }
}

SpringTaskDemo.java

import com.lhf.springboot.util.RandomUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.util.Date;


@Component
public class SpringTaskDemo {

    private final Logger logger = LoggerFactory.getLogger(SpringTaskDemo.class);

    @Scheduled(cron = "0/5 * * * * * ")
    public void scheduledCron(){
        logger.info("===>>使用cron表达式实现定时任务:" + System.currentTimeMillis());
    }

    @Scheduled(fixedRate = 6000)
    public void scheduledFixedRate(){
        logger.info("===>>使用fixedRate实现定时任务: " + RandomUtils.getRandomString(8));
    }

    @Scheduled(fixedDelay = 7000)
    public void scheduledFixedDelay(){
        logger.info("===>>使用fixedDelay实现定时任务: " + new Date() + " -- " +  RandomUtils.getRandomString(4));
    }
}

(5)Timer实现定时任务

TimerDemo.java

import com.lhf.springboot.util.RandomUtils;

import java.util.Timer;
import java.util.TimerTask;


public class TimerDemo {

   public void timerJob(){
       TimerTask timerTask = new TimerTask() {
           @Override
           public void run() {
               System.out.println("Timer Job: " + RandomUtils.getRandomString());
           }
       };
       Timer timer = new Timer();
       //每3秒执行一次
       timer.schedule(timerTask, 10, 3000);
   }
}

(6)工具类

RandomUtils.java——随机生成字符串工具类

import java.util.Random;


public class RandomUtils {
    public static String getRandomString(int length){
        //1.  定义一个字符串(A-Z,a-z,0-9)即62个数字字母;
        //String str="zxcvbnmlkjhgfdsaqwertyuiopQWERTYUIOPASDFGHJKLZXCVBNM1234567890";
        String str="用我三生烟火,换你一世迷离。长街长,烟花繁,你挑灯回看,短亭短,红尘辗,我把萧再叹。终是谁使弦断,花落肩头,恍惚迷离多少红颜悴,多少相思碎,唯留血染墨香哭乱冢。苍茫大地一剑尽挽破,何处繁华笙歌落。斜倚云端千壶掩寂寞,纵使他人空笑我。任他凡事清浊,为你一笑间轮回甘堕。寄君一曲,不问曲终人聚散。谁将烟焚散,散了纵横的牵绊。听弦断,断那三千痴缠。坠花湮,湮没一朝风涟。花若怜,落在谁的指尖。灯火星星,人声杳杳,歌不尽乱世烽火。如花美眷,似水流年,回得了过去,回不了当初。似此星辰非昨夜,为谁风露立中宵。蝴蝶很美,终究蝴蝶飞不过沧海。山河拱手,为君一笑 。待浮花浪蕊俱尽,伴君幽独。";

        //2.  由Random生成随机数
        Random random=new Random();
        StringBuffer sb=new StringBuffer();
        //3.  长度为几就循环几次
        for(int i=0; i

(7)启动类

import com.lhf.springboot.scheduled.ScheduledExecutorServiceDemo;
import com.lhf.springboot.springTask.SpringTaskDemo;
import com.lhf.springboot.timer.TimerDemo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;

@SpringBootApplication
@EnableScheduling   //注解开启对定时任务的支持
public class SpringBootTaskJobApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringBootTaskJobApplication.class, args);

        TimerDemo timerDemo = new TimerDemo();
        timerDemo.timerJob();

        ScheduledExecutorServiceDemo sch = new ScheduledExecutorServiceDemo();
        sch.scheduledJob();

        SpringTaskDemo st = new SpringTaskDemo();
        st.scheduledCron();
        st.scheduledFixedRate();
        st.scheduledFixedDelay();

    }

}

三、启动项目,运行效果如下:

发文不易,如果对你有帮助,请点个赞,感谢你的支持!有问题可以留言!


结束语:人生伟业的建立,不在能知,乃在能行。能行需要坚持,并且认准目标,勇敢前行!


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/234268.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号