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,还有诗与远方和妹子!!!
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章