springboot使用 @EnableScheduling、@Scheduled開啟定時任務


1.在main啟動項添加一個注解@EnableScheduling

package com.example.springmybatis;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;

@EnableScheduling
@SpringBootApplication
//@MapperScan("com.example.springmybatis.dao")
public class SpringMybatisApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringMybatisApplication.class, args);
    }
}

2.在類中添加@Component,方法上添加@Scheduled

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

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

@Component
public class SchedulerTask {
    //想要開啟定時任務,必須在啟動頁加上@EnableScheduling
    @Scheduled(cron="30 10 1 * * ?")
    public void aTask(){
        try {
            DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            System.out.println(sdf.format(new Date())+"*********A任務每20秒執行一次進入測試");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

3.cron表達式含義:

 * 0 0 10,14,16 * * ?每天上午10點、下午兩點、下午4點整觸發
 0 0/30 9-17 * * ? 每天朝九晚五內每隔半小時觸發
 0 15 10 ? * MON-FRI 周一至周五的上午10:15觸發
 0 0/5 * * * ?每5分鍾觸發
 10 0/5 * * * ?每隔5分鍾的第10秒觸發(即10:00:10、10:05:10、10:10:10等)
 30 * * * * ? 每半分鍾觸發
 30 10 * * * ? 每小時的10分30秒觸發
 30 10 1 * * ? 每天1點10分30秒觸發
 30 10 1 20 * ? 每月20號1點10分30秒觸發
 30 10 1 20 10 ? * 每年10月20號1點10分30秒觸發
 30 10 1 20 10 ? 2011 2011年10月20號1點10分30秒觸發
 30 10 1 ? 10 * 2011 2011年10月每天1點10分30秒觸發
 30 10 1 ? 10 SUN 2011 2011年10月每周日1點10分30秒觸發
 15,30,45 * * * * ? 每15秒,30秒,45秒時觸發
 15-45 * * * * ? 15到45秒內,每秒都觸發
 15/5 * * * * ? 每分鍾的每15秒開始觸發,每隔5秒觸發一次
 15-30/5 * * * * ? 每分鍾的15秒到30秒之間開始觸發,每隔5秒觸發一次
 0 0/3 * * * ? 每小時的第0分0秒開始,每三分鍾觸發一次
 0 15 10 ? * MON-FRI 星期一到星期五的10點15分0秒觸發
 0 15 10 L * ? 每個月最后一天的10點15分0秒觸發
 0 15 10 LW * ? 每個月最后一個工作日的10點15分0秒觸發
 0 15 10 ? * 5L 每個月最后一個星期四的10點15分0秒觸發
 0 15 10 ? * 5#3 每個月第三周的星期四的10點15分0秒觸發

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM