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

spring定时任务

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

spring定时任务

文章目录
      • 一、定时任务
      • 1、cron表达式
      • 2、cron示例
      • 3、SpringBoot整合

一、定时任务 1、cron表达式

语法:秒 分 时 日 月 周 年
(其中“年”Spring不支持,也就是说在spring定时任务中只能设置:秒 分 时 日 月 周)

2、cron示例


3、SpringBoot整合

@EnableScheduling
@Scheduled

实例:

package com.xunqi.gulimall.seckill.scheduled;

import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;





@Slf4j
@Component
@EnableScheduling
public class HelloScheduled {

    
     @Scheduled(cron = "*/1 * * * * ?")
     public void hello() {
         log.info("hello...");
         try { TimeUnit.SECONDS.sleep(3); } catch (InterruptedException e) { e.printStackTrace(); }

     }

}

定时任务默认是阻塞的线程,也就是说即使你设置成每一秒执行一次,但是方法内部的业务时间需要5秒才能执行完,也会造成定时任务每6秒才能执行一次。

  • 当然我们可以开启异步线程:
    @EnableAsync
    @Async

实例:

package com.xunqi.gulimall.seckill.scheduled;

import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;





@Slf4j
@Component
@EnableAsync
@EnableScheduling
public class HelloScheduled {

    
     @Async
     @Scheduled(cron = "*/1 * * * * ?")
     public void hello() {
         log.info("hello...");
         try { TimeUnit.SECONDS.sleep(3); } catch (InterruptedException e) { e.printStackTrace(); }

     }
}

这样就会开启异步线程,并且是非阻塞线程,因为每次都会开启一个线程来执行,我们可以看一下源码配置的截图,这个就是异步执行的默认配置,核心线程数是8,最大线程数是无限大,这时如果一直每秒执行一次,则会造成服务器资源耗尽。

当然,我们可以在配置文件中进行定时任务线程池的设定:
#核心线程数
spring.task.execution.pool.core-size=20
#最大线程数
spring.task.execution.pool.max-size=50
#队列大小
spring.task.execution.pool.queue-capacity=10000

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

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

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