1. 程式人生 > >spring boot 通過spring 中的@Scheduled註解實現定時任務

spring boot 通過spring 中的@Scheduled註解實現定時任務

spring boot 執行定時任務很簡單,首先只需在啟動類中加入@EnableScheduling註解,

import org.springframework.boot.SpringApplication;

import org.springframework.scheduling.annotation.EnableScheduling;

import org.springframework.cloud.client.SpringCloudApplication;

@EnableScheduling

@SpringCloudApplication
public class DatumApplication {

    /**
     * 程式主方法,啟動一個spring應用
     *
     *
     * @param args
     */
    public static void main(String[] args) {
        SpringApplication.run(DatumApplication.class, args);
    }

}

新增一個定時類,在方法上新增@Scheduled註解,定時  執行任務。


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

/**
 * 定時執行任務
 *
 * @author hxc
 */
@Component
public class SchedulerFile {

    /**
     * 每天凌晨零點執行一次定時任務
     * 注意定時方法不能有引數,加上引數會報錯。報Only no-arg methods may be annotated with @Scheduled 錯誤
     * @author hxc
     */
    @Scheduled(cron = "0 0 0 1/1 * ?")
    public void statusCheck() {

          System.out.println("開始執行任務********");

          //定時任務任務內容

          System.out.println("結束執行任務********");
    }
}