Springboot學習筆記(二)-定時任務

springboot中要使用定時任務須要在配置類或啓動類上標註註解@EnableScheduling,並在定時執行的無參方法上標註註解@Scheduled,程序啓動後會根據@Scheduled所提供的信息定時執行。spring

Scheduled參數

參數名 含義
cron = "* * * * * ?" 每秒執行
zone 時區,默認爲本地時區TimeZone.getDefault()
fixedDelay = 1000 上次任務執行完成後1秒開始
fixedDelayString = "1000" 等同fixedDelay = 1000
fixedRate = 1000 每秒執行
fixedRateString = "1000" 等同fixedRate = 1000
initialDelay = 1000 初始延時1秒執行
initialDelayString = "1000" 等同initialDelay = 1000

cron表達式

不用記,網上有在線cron生成器springboot

**String
公司規定的代碼規範中不容許使用魔法數字,能夠用這些參數規避。

代碼

@Component
public class ScheduledHelloTask {
    private static final Logger LOGGER = LoggerFactory.getLogger(ScheduledHelloTask.class);

    private int getSecond() {
        return Calendar.getInstance().get(Calendar.SECOND);
    }

    // 每秒執行
    @Scheduled(cron = "* * * * * ?", zone = "Asia/Shanghai")
    public void sayHello() {
        LOGGER.info("Hello World!");
    }

    // 任務執行完成後延時1秒開始
    @Scheduled(fixedDelay = 1000)
    public void sayHello1() throws InterruptedException {
        LOGGER.info(getSecond() + "春暖花開~");
        Thread.sleep(1000);
    }

    // 每秒執行,效果等同{cron = "* * * * * ?"}
    @Scheduled(initialDelay = 2000, fixedRate = 1000)
    public void sayHello2() throws InterruptedException {
        LOGGER.info(getSecond() + "你好~");
    }
}

關閉

有時候咱們在獲得本身須要的結果後想關閉定時任務,好比經過前臺發送連接來開啓上面的打印Hello World!任務,但願它執行10次後關閉。
此時就不能在類ScheduledHelloTask上添加@Component了, 由於咱們須要動態註冊bean來實現。改造以下:app

@EnableScheduling
public class ScheduledHelloTask {
    private static final Logger LOGGER = LoggerFactory.getLogger(ScheduledHelloTask.class);
    private AtomicInteger atomicInteger = new AtomicInteger();

    public AtomicInteger getAtomicInteger() {
        return atomicInteger;
    }

    public void setAtomicInteger(AtomicInteger atomicInteger) {
        this.atomicInteger = atomicInteger;
    }

    // 每秒執行
    @Scheduled(cron = "* * * * * ?", zone = "Asia/Shanghai")
    public void sayHello() {
        int count = atomicInteger.incrementAndGet();
        LOGGER.info("第" + count + "次:Hello World!");
    }
}

添加ScheduleController,代碼以下:this

@RestController
public class ScheduleController {
    private static final String BEAN_NAME = "scheduledHelloTask";

    @GetMapping
    public String sayHi() throws InterruptedException {
        AnnotationConfigApplicationContext applicationContext =
                new AnnotationConfigApplicationContext();
        if (!applicationContext.containsBean(BEAN_NAME)) {
            applicationContext.register(ScheduledHelloTask.class);
        }
        applicationContext.refresh();
        while (applicationContext.containsBean(BEAN_NAME)) {
            if (applicationContext.getBean(ScheduledHelloTask.class).getAtomicInteger().get() == 10) {
                applicationContext.removeBeanDefinition(BEAN_NAME);
            }
        }
        return "success";
    }
}

兩次訪問localhost:8080,結果以下:
atom

預期效果已實現!代碼規範

相關文章
相關標籤/搜索