Springboot学习笔记(二)-定时任务

springboot中要使用定时任务需要在配置类或启动类上标注注解@EnableScheduling,并在定时执行的无参方法上标注注解@Scheduled,程序启动后会根据@Scheduled所提供的信息定时执行。

Scheduled参数

参数名 含义
cron = "* * * * * ?" 每秒执行
zone 时区,默认为本地时区TimeZone.getDefault()
fixedDelay = 1000 上次任务执行完成后1秒开始
fixedDelayString = "1000" 等同fixedDelay = 1000
fixedRate = 1000 每秒执行
fixedRateString = "1000" 等同fixedRate = 1000
initialDelay = 1000 初始延时1秒执行
initialDelayString = "1000" 等同initialDelay = 1000

cron表达式

不用记,网上有在线cron生成器

**String
公司规定的代码规范中不允许使用魔法数字,可以用这些参数规避。

代码

@Component
public class ScheduledHelloTask {
    private static final Logger LOGGER = LoggerFactory.getLogger(ScheduledHelloTask.class);

    private int getSecond() {
        return Calendar.getInstance().get(Calendar.SECOND);
    }

    // 每秒执行
    @Scheduled(cron = "* * * * * ?", zone = "Asia/Shanghai")
    public void sayHello() {
        LOGGER.info("Hello World!");
    }

    // 任务执行完成后延时1秒开始
    @Scheduled(fixedDelay = 1000)
    public void sayHello1() throws InterruptedException {
        LOGGER.info(getSecond() + "春暖花开~");
        Thread.sleep(1000);
    }

    // 每秒执行,效果等同{cron = "* * * * * ?"}
    @Scheduled(initialDelay = 2000, fixedRate = 1000)
    public void sayHello2() throws InterruptedException {
        LOGGER.info(getSecond() + "你好~");
    }
}

关闭

有时候我们在得到自己需要的结果后想关闭定时任务,比如上面的打印Hello World!任务,希望它执行10次后关闭。
可以通过通过销毁bean的方式关闭定时任务:

@Component
public class ScheduledHelloTask implements ApplicationContextAware {
    private static final Logger LOGGER = LoggerFactory.getLogger(ScheduledHelloTask.class);
    private ApplicationContext applicationContext;
    private AtomicInteger atomicInteger = new AtomicInteger();

    // 每秒执行
    @Scheduled(cron = "* * * * * ?", zone = "Asia/Shanghai")
    public void sayHello() {
        int count = atomicInteger.incrementAndGet();
        if (count <= 10) {
            LOGGER.info("第" + count + "次:Hello World!");
            return;
        }
        // 通过销毁bean的方式关闭定时任务
        applicationContext.getAutowireCapableBeanFactory().destroyBean(this);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}

猜你喜欢

转载自www.cnblogs.com/yw0219/p/8976125.html