SpringBoot入門之定時任務

這一篇中,實現一個簡單的功能:定時任務。
實現這個功能主要用到3個註解:@Component,@Scheduled,@EnableScheduling。
其中@Component表示這個類是一個組件能夠被Spring容器自動檢測掃描到;@Scheduled表示這個方法是個定時任務方法,同時能夠配置定時參數;@EnableScheduling表示會建立後臺執行器,去執行定時任務。
下面寫一個小demo,每隔1秒鐘打印當前的時間。java

package com.spring.hello;

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;


/**
 * Created by zhangyi on 2017/3/30.
 */
@Component
public class ScheduledTasks {

    private static final Logger log= LoggerFactory.getLogger(ScheduledTasks.class);
    private static final SimpleDateFormat sdf=new SimpleDateFormat("HH:mm:ss");

    @Scheduled(fixedRate = 1000) //fixedRate這個參數表示每隔多少毫秒執行一次,1000也就是1000毫秒=1秒
    public void reportCurrentTime(){
        log.info("Current time is {}",sdf.format(new Date()));
    }
}
package com.spring;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;

/**
 * Created by zhangyi on 2017/3/29.
 */
@SpringBootApplication
@EnableScheduling
public class Application {

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

}

啓動以後,就能夠在控制檯看到輸出了,每隔1秒鐘打印一次當前時間 輸入圖片說明spring

相關文章
相關標籤/搜索