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秒觸發
複製代碼

 

程序員的眼裏,不止有代碼和bug,還有詩與遠方和妹子!!!
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章