@Scheduled 定时

此文章记录在spring boot项目中的使用

1,在项目的启动类中加注解@EnableScheduling,表示此项目可以进行定时

@SpringBootApplication
@EnableScheduling
public class SavepicApplication {

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

}

2,在要定时的类中

package com.bonc.savepic.save;

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

/**
 * @Author clj
 * @SinceDate 2019/3/26 17:23
 * @Description
 */
@Component
public class SaveSchedule {

    /**
     * 此方法每隔20秒执行一次
     */
    @Scheduled(cron = "0/20 * * * * *")
    public void savePic(){
        System.out.println("开始");
    }
}

3,@Scheduled(cron = " ")表达式

1.Seconds Minutes Hours DayofMonth Month DayofWeek Year
2.Seconds Minutes Hours DayofMonth Month DayofWeek

注:项目中使用第一种(7位)的时候启动报错,说只能有6个,还未找到原因

常用例子:

每隔5秒执行一次:"*/5 * * * * ?"

每隔1分钟执行一次:"0 */1 * * * ?"

每天23点执行一次:"0 0 23 * * ?"

每天凌晨1点执行一次:"0 0 1 * * ?"

每月1号凌晨1点执行一次:"0 0 1 1 * ?"

每月最后一天23点执行一次:"0 0 23 L * ?"

每周星期天凌晨1点实行一次:"0 0 1 ? * L"

在26分、29分、33分执行一次:"0 26,29,33 * * * ?"

每天的0点、13点、18点、21点都执行一次:"0 0 0,13,18,21 * * ?"

表示在每月的1日的凌晨2点调度任务:"0 0 2 1 * ? *"

表示周一到周五每天上午10:15执行作业:"0 15 10 ? * MON-FRI" 

表示2002-2006年的每个月的最后一个星期五上午10:15执行:"0 15 10 ? 6L 2002-2006"

原文地址:https://www.cnblogs.com/cailijuan/p/10601573.html