• 浅谈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

    从上面的打印可以看出:

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

  • 相关阅读:
    C语言——通讯录管理系统
    稍微有点坑的bfs
    JDBC快速入门
    当长假来临,如何定向应用AI?科技力量变革您的假日生活!
    初次接触Sharding-JDBC并实际应用
    C++中的无限循环
    【Spring Cloud Alibaba】seata分布式事务官方入门案例(实战版)
    操作系统学习知识点(1)
    解决使用keras训练模型Could not create cudnn handle: CUDNN_STATUS_INTERNAL_ERROR报错问题
    LCT (link cut tree)动态树学习
  • 原文地址:https://blog.csdn.net/weixin_44107140/article/details/126457321