SpringBoot 定时任务Scheduled

一。引入了spring-boot-starter包即可,无需额外jar包:

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

二。启动类添加注解@EnableScheduling:

@SpringBootApplication//@EnableAutoConfiguration 
@EnableScheduling//支持定时任务
public class SpringBootApplication {

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

}

三。定时任务代码编写:

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

import java.util.Date;


@Component
public class DemoSchedule {

    @Scheduled(cron = "0 0/1 * * * ?")//每隔一分钟执行
    public void test1() {
        System.out.println("定时任务执行:" + new Date());
    }
    
}

其中,cron表达式是spring内置支持的时间表达式,详解待续,可直接百度“在线cron”,可帮你自动生成。 

猜你喜欢

转载自blog.csdn.net/yzh_1346983557/article/details/86244486