1. 程式人生 > >SpringBoot使用註解形式定時執行同步任務

SpringBoot使用註解形式定時執行同步任務

1、SpringBoot定時執行同步任務可以使用org.springframework.scheduling包下的@EnableScheduling以及@Scheduled註解來實現,程式碼如下:


@Configuration
@EnableScheduling

public class SynchTask {

    @Scheduled(cron = "0 */1 *  * * * ")
    public void myTask() {

        try {
            Thread.sleep(1000 * 60);
            System.out.println(" Tasks Examples By Cron: The time is now " + dateFormat().format(new Date()));
        }
        catch (InterruptedException e) {

            e.printStackTrace();
        }
        System.out.println();
    }

    private SimpleDateFormat dateFormat() {
        return new SimpleDateFormat("HH:mm:ss");
    }

}

@EnableScheduling 註解在類上,定義這是一個定時執行類,@Scheduled在執行方法上,@Configuration註解會在springBoot啟動時,將該類載入至spring容器中;cron = "0 */1 *  * * * ",cron表示式表示每分鐘執行一次,Thread.sleep(1000 * 60);表示業務執行時間,執行實際結果是每2分鐘執行一次,說明@EnableScheduling, @Scheduled註解是同步執行的

執行結果如下: