SpringBoot实现异步任务以及定时任务

简介: 在绝大多数的java应用中,很多场景都是采用的是同步的方式交互,那么一旦如果有第三方进行交互,则很有可能就会产生交互延迟的问题,那么这种时候就得考虑使用多线程,但是在Spring3以后它就已经内置了异步任务供我们使用。

前言


在绝大多数的java应用中,很多场景都是采用的是同步的方式交互,那么一旦如果有第三方进行交互,则很有可能就会产生交互延迟的问题,那么这种时候就得考虑使用多线程,但是在Spring3以后它就已经内置了异步任务供我们使用。


异步任务


在springboot中使用异步,只需要采用注解@EnableAysnc、@Aysnc这两个注解即可:


@EnableAsync注解表示开启对异步任务的支持;


@Async注解则是用来声明一个或多个异步任务,可以加在方法或者类上,加在类上表示这整个类都是使用这个自定义线程池进行操作;


使用案例


在springboot的启动类上,添加@EnableAsync注解表示开启异步任务支持:


@SpringBootApplication
@EnableConfigurationProperties
@EnableAsync
public class Main {
    public static final Logger logger = LoggerFactory.getLogger(Main.class);
    public static void main(String[] args) {
        logger.info("Spring Boot Beginning ...");
        SpringApplication.run(Main.class, args);
    }
}
复制代码


Service类的方法上添加@async注解:
@Servicepublic class AsyncService {    @Async //@Async注解来声明一个或多个异步任务,可以加在方法或者类上,加在类上表示这整个类都是使用这个自定义线程池进行操作    public void aysncService(){        System.out.println("今天是大年初一!"+System.currentTimeMillis());        try {            Thread.sleep(10000);        }catch (Exception e){            e.printStackTrace();        }        System.out.println("祝大家虎年大吉!"+System.currentTimeMillis());    }}
controller:
@RestControllerpublic class AsyncController {    @Autowired    AsyncService asyncService;    @GetMapping("/async")    public String asyncmethod1(){        asyncService.aysncService();        return "async success"+System.currentTimeMillis();    }}
地址栏输入:
http://localhost:8081/share/async
复制代码


运行结果如下:


微信截图_20220521204531.png


微信截图_20220521204541.png


控制台先执行页面跳转,10秒后输出祝大家虎年大吉,说明方法是异步执行的!


定时任务


在实际的很多应用场景中需要使用到一些定时任务。比如日志报告、定时邮件、定时预警等等。然而在Spring中也为我们提供了异步执行任务调度的方式,提供TaskExecutor、TaskScheduler接口。这里定时任务主要使用到了@EnableScheduling、@Scheduled这两个注解:


@EnableScheduling注解也是使用在SpringBootApplication主类上,表示开启定时任务

@Scheduled注解则是表示如何使用定时任务,这里主要有8个参数或者属性。


其源码如下:


@Target({ElementType.METHOD, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Repeatable(Schedules.class)
public @interface Scheduled {
    /**
     * A cron-like expression, extending the usual UN*X definition to include
     * triggers on the second as well as minute, hour, day of month, month
     * and day of week.  e.g. {@code "0 * * * * MON-FRI"} means once per minute on
     * weekdays (at the top of the minute - the 0th second).
     * @return an expression that can be parsed to a cron schedule
     * @see org.springframework.scheduling.support.CronSequenceGenerator
     */
    String cron() default "";
    /**
     * A time zone for which the cron expression will be resolved. By default, this
     * attribute is the empty String (i.e. the server's local time zone will be used).
     * @return a zone id accepted by {@link java.util.TimeZone#getTimeZone(String)},
     * or an empty String to indicate the server's default time zone
     * @since 4.0
     * @see org.springframework.scheduling.support.CronTrigger#CronTrigger(String, java.util.TimeZone)
     * @see java.util.TimeZone
     */
    String zone() default "";
    /**
     * Execute the annotated method with a fixed period in milliseconds between the
     * end of the last invocation and the start of the next.
     * @return the delay in milliseconds
     */
    long fixedDelay() default -1;
    /**
     * Execute the annotated method with a fixed period in milliseconds between the
     * end of the last invocation and the start of the next.
     * @return the delay in milliseconds as a String value, e.g. a placeholder
     * @since 3.2.2
     */
    String fixedDelayString() default "";
    /**
     * Execute the annotated method with a fixed period in milliseconds between
     * invocations.
     * @return the period in milliseconds
     */
    long fixedRate() default -1;
    /**
     * Execute the annotated method with a fixed period in milliseconds between
     * invocations.
     * @return the period in milliseconds as a String value, e.g. a placeholder
     * @since 3.2.2
     */
    String fixedRateString() default "";
    /**
     * Number of milliseconds to delay before the first execution of a
     * {@link #fixedRate()} or {@link #fixedDelay()} task.
     * @return the initial delay in milliseconds
     * @since 3.2
     */
    long initialDelay() default -1;
    String initialDelayString() default "";
}
复制代码


1、cron属性


cron表达式格式:


[秒] [分] [小时] [日] [月] [周] [年] //但是这里的年不是必须的域,可以省略[年],则一共6个域
second,minute,hour,day of month,month,day of week
复制代码


字段 允许值
允许的通配符
是否必填

0-59
, -* /
0-59 , -* /
小时 0-23 , -* /
日期 1-31 , -* ? / L W 
月份 1-12 , -* /
星期 0-7或SUN-SAT  , -* ? / L  #

1970-2099 , - * /


说明

1、* 表示所有值。例如:在分的字段上设置 *,表示每一分钟都会触发。


2、? 表示不指定值。使用的场景为不需要关心当前设置这个字段的值。例如:要在每月的10号触发一个操作,但不关心是周几,所以需要周位置的那个字段设置为”?” 具体设置为 0 0 0 10 * ?


3、- 表示区间。例如 在小时上设置 “10-12”,表示 10,11,12点都会触发。


4、, 表示指定多个值,例如在周字段上设置 “MON,WED,FRI” 表示周一,周三和周五触发


5、/ 用于递增触发。如在秒上面设置”5/15” 表示从5秒开始,每增15秒触发(5,20,35,50)。在日字段上设置’1/3’所示每月1号开始,每隔三天触发一次。


6、L 表示最后的意思。在日字段设置上,表示当月的最后一天(依据当前月份,如果是二月还会依据是否是润年[leap]), 在周字段上表示星期六,相当于”7”或”SAT”。如果在”L”前加上数字,则表示该数据的最后一个。例如在周字段上设置”6L”这样的格式,则表示“本月最后一个星期五”


7、W 表示离指定日期的最近那个工作日(周一至周五). 例如在日字段上置”15W”,表示离每月15号最近的那个工作日触发。如果15号正好是周六,则找最近的周五(14号)触发, 如果15号是周未,则找最近的下周一(16号)触发.如果15号正好在工作日(周一至周五),则就在该天触发。如果指定格式为 “1W”,它则表示每月1号往后最近的工作日触发。如果1号正是周六,则将在3号下周一触发。(注,”W”前只能设置具体的数字,不允许区间”-“)。


8、# 序号(表示每月的第几个周几),例如在周字段上设置”6#3”表示在每月的第三个周六.注意如果指定”#5”,正好第五周没有周六,则不会触发该配置(用在母亲节和父亲节再合适不过了) ;小提示:’L’和 ‘W’可以一组合使用。如果在日字段上设置”LW”,则表示在本月的最后一个工作日触发;周字段的设置,若使用英文字母是不区分大小写的,即MON与mon相同。


举例


cron = "*/10 * * * * ?" //每隔10秒执行一次:
cron = "* * * * * 0-7" //周一到周天每天每时每分每秒都执行一次
cron = "0-4 * * * * 0-7" //周一到周天每天每时每分1-5秒每秒都执行一次
复制代码


2. zone


时区,表示接收一个java.util.TimeZone#ID。cron表达式会基于该时区解析。默认是一个空字符串,即取服务器所在地的时区。比如我们一般使用的时区Asia/Shanghai。该字段我们一般留空。


3. fixedDelay


上一次执行完毕时间点之后多长时间再执行。


4. fixedDelayString


与 fixedDelay 意思相同,只是使用字符串的形式。唯一不同的是支持占位符。


5. fixedRate


上一次开始执行时间点之后多长时间再执行。


6. fixedRateString


与 5. fixedRate 意思相同,只是使用字符串的形式。唯一不同的是支持占位符。


7. initialDelay


第一次延迟多长时间后再执行。


8. initialDelayString


与 initialDelay 意思相同,只是使用字符串的形式。唯一不同的是支持占位符。


案例


同样的首先主类上要使用@EnableScheduling注解


@EnableScheduling //开启定时任务注解
public class SpringbootdemoApplication {
    private static final Logger logger = LoggerFactory.getLogger(SpringbootdemoApplication.class);
    public static void main(String[] args) {
        logger.info("===============项目启动了===============");
        SpringApplication.run(SpringbootdemoApplication.class, args);
        logger.info("===============启动成功了===============");
    }
}
复制代码


@RestController
public class SceduleController {
    @GetMapping("/say")
    @Scheduled(fixedDelay = 10000, initialDelay = 5000/*容器启动后延迟5秒后在执行一次定时器,以后每10秒再执行一次定时器*/)
    public String say(){
        System.out.println("你好"+System.currentTimeMillis());
        return "你好"+System.currentTimeMillis();
    }
    @GetMapping("/happynewyear")
    @Scheduled(cron = "0 18 16 * * ?"/*每天16点18执行一次*/)
    public String sayhappynewyear(){
        System.out.println("虎年大吉"+ LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        return "虎年大吉"+LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
    }
}
复制代码


现在时间是,16:17:


微信截图_20220521204603.png


运行结果:




020c57dea4774b9ab728439311b70775~tplv-k3u1fbpfcp-zoom-in-crop-mark_1304_0_0_0.webp.jpg


总结


任务是开发场景中很常见的,结合异步任务和定时任务能够实现很多的功能,而spring已经提供了关于定时任务和异步任务的功能,能够大大简化我们的开发。



目录
相关文章
|
25天前
|
Java 调度 Spring
SpringBoot实现多线程定时任务动态定时任务配置文件配置定时任务
SpringBoot实现多线程定时任务动态定时任务配置文件配置定时任务
44 0
|
1月前
|
druid Java 数据库
Spring Boot的定时任务与异步任务
Spring Boot的定时任务与异步任务
|
7天前
|
Java Spring 容器
SpringBoot 使用Quartz执行定时任务对象时无法注入Bean问题
SpringBoot 使用Quartz执行定时任务对象时无法注入Bean问题
10 1
|
25天前
|
Java Spring
SpringBoot+async异步调用接口以及几个任务同时完成和异步接口实现和调用
SpringBoot+async异步调用接口以及几个任务同时完成和异步接口实现和调用
24 0
|
1月前
|
JavaScript Java API
spring boot使用异步多线程
一文讲清楚spring boot如何结合异步多线程实现文件的导出这类耗时间的操作优化以及常用的场景,了解异步思想
31 0
spring boot使用异步多线程
|
3月前
|
SQL 分布式计算 Java
SpringBoot集成quartz调度linkis任务
SpringBoot集成quartz调度linkis任务
|
3月前
|
Java 调度 流计算
在使用Spring Boot启动Flink处理任务时
在使用Spring Boot启动Flink处理任务时【1月更文挑战第22天】【1月更文挑战第108篇】
56 1
|
3月前
|
Java 容器
SpringBoot 异步任务处理
SpringBoot 异步任务处理
16 0
|
3月前
|
Java 程序员 数据库
SpringBoot实现固定、动态定时任务 | 三种实现方式
SpringBoot实现固定、动态定时任务 | 三种实现方式
95 0
|
4月前
|
Java
Springboot整合Activity7:任务,历史任务,UEL表达式(三)
Springboot整合Activity7:任务,历史任务,UEL表达式(三)