Spring使用@Scheduled創建定時任務

使用@Scheduled創建定時任務

package com.xyt.springboot.tasks;

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

import java.text.SimpleDateFormat;
import java.util.Date;

@Component//注入spring容器
public class ScheduledTasks {
    private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");

    @Scheduled(fixedRate = 5000)//這個註解以毫秒爲單位的,
    public void reportCurrentTime() {
        System.out.println("現在時間:" + dateFormat.format(new Date()));
    }
}

在Spring Boot的主類中加入@EnableScheduling註解,啓用定時任務的配置

package com.xyt.springboot;

import com.xyt.springboot.config.member.MemberConfig;
import com.xyt.springboot.config.member.MemberDatasourceConfig;
import com.xyt.springboot.config.order.OrderConfig;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.scheduling.annotation.EnableScheduling;

@SpringBootApplication
@EnableScheduling//開啓任務定時器
public class AppSpringBootMybatis {
    public static void main(String[] args) {
        SpringApplication.run(AppSpringBootMybatis.class, args);
    }
}

spring自帶的定時器 只適合用於簡單的定時任務/複雜的定時任務需要引入其它插件來實現

發佈了31 篇原創文章 · 獲贊 1 · 訪問量 6523
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章