Scheduled实现定时任务

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/yjn1995/article/details/100533136

前言

本文主要讲解如何使用Spring实现定时任务调度。在读完这篇文章后,你将会了解到如何使用@Scheduled注解实现每隔一段时间执行任务。

创建项目

首先创建一个Spring Boot工程,无需导入任何依赖

创建一个定时任务类

每5秒打印一次时间

package com.yjn.schedule;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;

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

    private static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");

    @Scheduled(fixedRate = 5000)
    public void reportCurrentTime() {
        log.info("The time is now {}", dateFormat.format(new Date()));
    }
}

@Scheduled注解定义了特定方法什么时候运行。注意:本例使用fixedRate,它指定方法调用之间的间隔,从每次调用的开始时间开始测量。还有其他选项,比如fixedDelay,它指定从任务完成开始测量的调用之间的间隔。还可以使用@Scheduled(cron="…")表达式进行更复杂的任务调度。

开启定时任务

我们通过在SpringBoot启动类上添加@EnableScheduling注解来开启定时任务

@SpringBootApplication
@EnableScheduling
public class ScheduleApplication {

    public static void main(String[] args) {
        SpringApplication.run(ScheduleApplication.class, args);
    }

}

测试

启动项目出现以下输出则说明成功
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/yjn1995/article/details/100533136
今日推荐