Spring Boot项目添加定时器timer

Spring Boot项目整合定时器其实很简单,写一个简易版。

首先创建一个timer类。

package com.cloudjoyclub.sharespace.timer;

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


@Component
public class SponsorActivityTimer {

    // 执行方法
    @Scheduled(cron = "0 0/1 * * * ? ")
    public void run() {
        //执行的业务逻辑
    }
}

注意要加上@Component注解,让Spring Boot可以扫描到此类
@Scheduled注解中可以添加时间表达式,这里cron = "0 0/1 * * * ? "表示一分钟执行一次run方法,具体时间表达式用法可以自行百度。

然后再Spring Boot启动类中添加@EnableScheduling注解,表示此项目支持定时器用法。

@EnableScheduling   
@SpringBootApplication
public class Application {

        public static void main(String[] args) {
            TimeZone.setDefault(TimeZone.getTimeZone("Asia/Shanghai"));
            SpringApplication.run(Application.class, args);
        }
}

你可能感兴趣的:(Spring Boot项目添加定时器timer)