@Scheduled & @EnableScheduling:定时器核心注解,用来实现定时器功能

spring中 @Scheduled & @EnableScheduling 这2个注解,可以用来快速开发定时器,使用特别的简单。

如何使用?

用法

1、需要定时执行的方法上加上@Scheduled注解,这个注解中可以指定定时执行的规则,稍后详细介绍。

2、Spring容器中使用@EnableScheduling开启定时任务的执行,此时spring容器才可以识别@Scheduled标注的方法,然后自动定时执行。

案例

db中有很多需要推送的任务,然后将其检索出来,推送到手机端,来个定时器,每秒一次从库中检测需要推送的消息,然后推送到手机端。

package com.javacode2018.scheduled.demo1;

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
public class PushJob {

    //推送方法,每秒执行一次
    @Scheduled(fixedRate = 1000)
    public void push() throws InterruptedException {
        System.out.println("模拟推送消息," + System.currentTimeMillis());
    }

}

来个spring配置类,需要使用@EnableScheduling标注

package com.javacode2018.scheduled.demo1;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.scheduling.annotation.EnableScheduling;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;

@ComponentScan
@EnableScheduling //在spring容器中启用定时任务的执行
public class MainConfig1 {

    @Bean
    public ScheduledExecutorService scheduledExecutorService() {
        return Executors.newScheduledThreadPool(20);
    }
}

测试类

package com.javacode2018.scheduled;

import com.javacode2018.scheduled.demo1.MainConfig1;
import org.junit.Test;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import java.util.concurrent.TimeUnit;

public class ScheduledTest {
    @Test
    public void test1() throws InterruptedException {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
        context.register(MainConfig1.class);
        context.refresh();
        //休眠一段时间,房子junit自动退出
        TimeUnit.SECONDS.sleep(10000);
    }

}

运行输出,每秒会输出一次,如下:

模拟推送消息,1595840822998
模拟推送消息
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值