当前位置: 移动技术网 > IT编程>开发语言>Java > SpringBoot2.0 基础案例(04):定时任务和异步任务的使用方式

SpringBoot2.0 基础案例(04):定时任务和异步任务的使用方式

2019年06月11日  | 移动技术网IT编程  | 我要评论

一、定时任务

1、基本概念

按照指定时间执行的程序。

2、使用场景

数据分析
数据清理
系统服务监控

二、同步和异步

1、基本概念

同步调用
程序按照代码顺序依次执行,每一行程序都必须等待上一行程序执行完成之后才能执行;
异步调用
顺序执行时,不等待异步调用的代码块返回结果就执行后面的程序。

2、使用场景

短信通知
邮件发送
批量数据入缓存

三、springboot2.0使用定时器

1、定时器执行规则注解

@scheduled(fixedrate = 5000) :上一次开始执行时间点之后5秒再执行
@scheduled(fixeddelay = 5000) :上一次执行完毕时间点之后5秒再执行
@scheduled(initialdelay=1000, fixedrate=5000) :第一次延迟1秒后执行,之后按fixedrate的规则每5秒执行一次
@scheduled(cron="/5") :通过cron表达式定义规则

2、定义时间打印定时器

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") ;
    /**
     * 每3秒打印一次系统时间
     */
    @scheduled(fixeddelay = 3000)
    public void systemdate (){
        log.info("当前时间::::"+format.format(new date()));
    }
}

3、启动类开启定时器注解

@enablescheduling   // 启用定时任务
@springbootapplication
public class taskapplication {
    public static void main(string[] args) {
        springapplication.run(taskapplication.class,args) ;
    }
}

四、springboot2.0使用异步任务

1、编写异步任务类

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) ;
    /*
     * [ asynctask1-2] com.boot.task.config.asynctask : ======异步任务结束1======
     * [ asynctask1-1] com.boot.task.config.asynctask : ======异步任务结束0======
     */
    // 只配置了一个 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、指定异步任务执行的线程池

这里可以不指定,指定执行的线城池,可以更加方便的监控和管理异步任务的执行。

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-");
        /*
        线程池对拒绝任务的处理策略:这里采用了callerrunspolicy策略,
        当线程池没有处理能力的时候,该策略会直接在 execute 方法的调用线程中运行被拒绝的任务;
        如果执行程序已关闭,则会丢弃该任务
         */
        executor.setrejectedexecutionhandler(new threadpoolexecutor.callerrunspolicy());
        // 设置线程池关闭的时候等待所有任务都完成再继续销毁其他的bean
        executor.setwaitfortaskstocompleteonshutdown(true);
        // 设置线程池中任务的等待时间,如果超过这个时候还没有销毁就强制销毁,以确保应用最后能够被关闭,而不是阻塞住。
        executor.setawaitterminationseconds(600);
        return executor;
    }
}

3、启动类添加异步注解

@enableasync        // 启用异步任务
@springbootapplication
public class taskapplication {
    public static void main(string[] args) {
        springapplication.run(taskapplication.class,args) ;
    }
}

4、异步调用的测试接口

@restcontroller
public class taskcontroller {
    @resource
    private asynctask asynctask ;
    @requestmapping("/asynctask")
    public string asynctask (){
        asynctask.asynctask0();
        asynctask.asynctask1();
        return "success" ;
    }
}

五、源代码地址

github:知了一笑
https://github.com/cicadasmile/spring-boot-base


如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网