• 浅谈spring的@Scheduled定时任务(演示)


    spring的@Scheduled定时任务

    条件:

    • 没有参数
    • 没有返回值(void)

    使用步骤

    1. 项目启动类添加注解@EnableScheduled
    2. 编写定时任务方法,方法上用@Scheduled
    3. 当有多个定时任务,使用异步或者多线程处理

    关于cron:配置任务执行的时刻,任务开始前,先判断可否执行

    ,能就执行,否则跳过本次

    cron表达式生成:

    https://qqe2.com/cron/index

    注解属性

    • fixedRate:设定上一个任务开始时间到下一个任务的开始时间间隔(如果上一个任务没有完成时,spring会等待上一个任务执行完,并立即执行本次任务)
    • fixedDelay:设定上一个任务结束后间隔多久执行下一个任务

    创建个springboot项目简单测试一下

    启动类:

    @SpringBootApplication
    @EnableScheduling
    public class DemoApiApplication {
        public static void main(String[] args) {
            SpringApplication.run(DemoApiApplication.class, args);
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    定时器:

    @Component
    @Slf4j
    public class TestTask {
        @Scheduled(cron ="0/5 * * * * ?")
        public void doTask(){
            System.out.println("task run.....");
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    启动效果:

    2022-08-08 14:29:55.595  INFO 19912 --- [           main] com.example.demoapi.DemoApiApplication   : Started DemoApiApplication in 1.577 seconds (JVM running for 2.166)
    task run.....
    task run.....
    task run.....
    task run.....
    
    • 1
    • 2
    • 3
    • 4
    • 5

    spring的定时器默认单线程,任务之间不会并行执行,即便是固定频率,下一次的任务也需要等上一次任务执行完毕,之后再开始。

    注解:@Async

    用途:使任务能异步多线程执行

    使用步骤:

    1. 在启动类添加配置注解@Async
    2. 定时器方法也用@Async注解

    测试:

    @Scheduled(fixedDelay = 1000)
    @Async
    public void doTask() throws InterruptedException {
        System.out.println("task run.....");
        System.out.println(Thread.currentThread().getName());
        Thread.sleep(3000);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    控制台输出:

    2022-08-08 14:57:33.162  INFO 9280 --- [           main] com.example.demoapi.DemoApiApplication   : Started DemoApiApplication in 1.646 seconds (JVM running for 2.226)
    task run.....
    task-1
    task run.....
    task-2
    task run.....
    task-3
    task run.....
    task-4
    task run.....
    task-5
    task run.....
    task-6
    task run.....
    task-7
    task run.....
    task-8
    task run.....
    task-1
    task run.....
    task-2
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21

    从上面的打印可以看出:

    即使前面的任务还没有完成,定时任务仍以固定的频率开始。而且线程名也不一样,通过多线程来执行。

  • 相关阅读:
    Sora引领AI生成模型新篇章,视频人工AI创造新视野
    配置项目外网访问(公网IP+DDNS)
    基于Spring Security添加流控
    Pointers
    BC1.2 PD协议
    快速排序(重点)
    el-menu 导航栏学习-for循环封装(2)
    VR全景技术,为养老院宣传推广带来全新变革
    音频文件播放与暂停
    计算机毕设(附源码)JAVA-SSM基于框架的毕业生就业管理系统
  • 原文地址:https://blog.csdn.net/weixin_44107140/article/details/126457321