Spring高級話題-計劃任務

一、什麼是計劃任務

就相當於一個定時器,可以使代碼在固定的日期時間執行

二、在Spring中如何使用計劃任務

使用@EnableScheduling開啓對計劃任務的支持
使用@Scheduled聲明一個計劃任務 (支持多類型,包括cron, fixDelay, fixRate)

三、scheduleDemo

配置類

package com.cactus.demo.schedule;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;

/**
 * Created by liruigao
 * Date: 2019-12-05 15:48
 * Description:
 */

@Configuration
@ComponentScan("com.cactus.demo.schedule")
@EnableScheduling
public class ScheduleConfig {
}

執行類

package com.cactus.demo.schedule;

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

import java.util.Date;

/**
 * Created by liruigao
 * Date: 2019-12-05 15:45
 * Description:
 */

@Service
public class ScheduleDemo {
    @Scheduled(fixedDelay = 3000)
    public void taskOne() {
        System.out.println("taskOne - " + new Date());
    }

    @Scheduled(cron = "0 53 15 ? * *")
    public void taskTwo() {
        System.out.println("taskTwo - " + new Date());
    }
}

Main

package com.cactus.demo.schedule;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

/**
 * Created by liruigao
 * Date: 2019-12-05 15:49
 * Description:
 */


public class Main {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ScheduleConfig.class);
        ScheduleDemo scheduleDemo = context.getBean(ScheduleDemo.class);
    }
}

Result

taskOne - Mon Dec 09 15:04:53 CST 2019
taskOne - Mon Dec 09 15:04:56 CST 2019
taskOne - Mon Dec 09 15:04:59 CST 2019
taskTwo - Mon Dec 09 15:05:00 CST 2019
taskOne - Mon Dec 09 15:05:02 CST 2019
taskOne - Mon Dec 09 15:05:05 CST 2019
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章