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

springboot:定时任务和异步任务的使用方式

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

springboot:定时任务和异步任务的使用方式

springboot:定时任务和异步任务的使用方式 一、定时任务

1.基本概念:安装指定时间执行的程序

2.使用场景

  • 数据分析
  • 数据清理
  • 系统服务监控
二、同步和异步

1.基本概念

同步调用:程序安装代码顺序依次执行,每一行程序必须等待上一行程序执行完之后才能执行

异步调用:顺序执行时,不等待异步调用的代码块返回结果就执行后面的程序。

2.使用场景

  • 短信通知
  • 邮件发送
  • 批量数据入缓存
三、springboot使用定时器 1、定时器执行规则注解
@Scheduled(fixedRate = 5000) :上一次开始执行时间点之后5秒再执行
@Scheduled(fixedDelay = 5000) :上一次执行完毕时间点之后5秒再执行
@Scheduled(initialDelay=1000, fixedRate=5000) :第一次延迟1秒后执行,之后按fixedRate的规则每5秒执行一次
@Scheduled(cron="/5") :通过cron表达式定义规则

core表达式在线生成地址

2、时间定时任务
package com.mye.hl17springboottask.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.text.SimpleDateFormat;
import java.util.Date;


@Component
public class Timetask {
    Logger LOG = LoggerFactory.getLogger(Timetask.class.getName()) ;
    private static final SimpleDateFormat format =
            new SimpleDateFormat("yyyy-MM-dd HH:mm:ss") ;

    

    
    @Scheduled(fixedDelay = 3000)
    public void systemDate (){
        LOG.info("当前时间::::"+format.format(new Date()));
    }
}
3、启动类上开启定时器注解
package com.mye.hl17springboottask;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;

@EnableScheduling   // 启用定时任务
@SpringBootApplication
public class Hl17SpringbootTaskApplication {

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

}

测试结果

四、springboot使用异步任务 1、定义异步任务类
package com.mye.hl17springboottask.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

@Component
public class AsyncTask {
    private static final Logger LOGGER = LoggerFactory.getLogger(AsyncTask.class) ;
    
    // 只配置了一个 asyncExecutor1 不指定也会默认使用
    @Async
    public void asyncTask0 () {
        try{
            Thread.sleep(5000);
        }catch (Exception e){
            e.printStackTrace();
        }
        LOGGER.info("======异步任务结束0======");
    }
    @Async("asyncExecutor1")
    public void asyncTask1 () {
        try{
            Thread.sleep(5000);
        }catch (Exception e){
            e.printStackTrace();
        }
        LOGGER.info("======异步任务结束1======");
    }
}
2、创建线程池
package com.mye.hl17springboottask.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

@Configuration
public class TaskPoolConfig {
    @Bean("asyncExecutor1")
    public Executor taskExecutor1 () {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        // 核心线程数10:线程池创建时候初始化的线程数
        executor.setCorePoolSize(10);
        // 最大线程数20:线程池最大的线程数,只有在缓冲队列满了之后才会申请超过核心线程数的线程
        executor.setMaxPoolSize(20);
        // 缓冲队列200:用来缓冲执行任务的队列
        executor.setQueueCapacity(200);
        // 允许线程的空闲时间60秒:当超过了核心线程出之外的线程在空闲时间到达之后会被销毁
        executor.setKeepAliveSeconds(60);
        // 线程池名的前缀:设置好了之后可以方便定位处理任务所在的线程池
        executor.setThreadNamePrefix("asyncTask1-");
        
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        // 设置线程池关闭的时候等待所有任务都完成再继续销毁其他的Bean
        executor.setWaitForTasksToCompleteOnShutdown(true);
        // 设置线程池中任务的等待时间,如果超过这个时候还没有销毁就强制销毁,以确保应用最后能够被关闭,而不是阻塞住。
        executor.setAwaitTerminationSeconds(600);
        return executor;
    }
}
3、启动类上启动异步任务
@EnableAsync
@SpringBootApplication
public class Hl17SpringbootTaskApplication {

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

}
4.测试类
package com.mye.hl17springboottask;

import com.mye.hl17springboottask.config.AsyncTask;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest(classes = Hl17SpringbootTaskApplication.class)
public class AsyncTaskTest {

    @Autowired
    private AsyncTask asyncTask ;

    @Test
    public void test01(){
        asyncTask.asyncTask0();
        asyncTask.asyncTask1();
    }
}

这里执行俩个任务的时间是一样的说明是异步执行的

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

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

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