@Scheduled在springboot中的使用

@Scheduled注解参数:

  • cron:cron表达式,指定任务在特定时间执行;
  • fixedDelay:表示上一次任务执行完成后多久再次执行,参数类型为long,单位ms;
  • fixedDelayString:与fixedDelay含义一样,只是参数类型变为String;
  • fixedRate:表示按一定的频率执行任务,参数类型为long,单位ms;
  • fixedRateString: 与fixedRate的含义一样,只是将参数类型变为String;
  • initialDelay:表示延迟多久再第一次执行任务,参数类型为long,单位ms;
  • initialDelayString:与initialDelay的含义一样,只是将参数类型变为String;
  • zone:时区,默认为当前时区。

cron表达式语法

[秒] [分] [小时] [日] [月] [周] [年]
序号 说明 必填 允许填写的值 允许的通配符
1 0-59 , - * /
2 0-59 , - * /
3 0-23 , - * /
4 1-31 , - * ? / L W
5 1-12 / JAN-DEC , - * /
6 1-7 or SUN-SAT , - * ? / L #
7 1970-2099 , - * /

通配符说明:

  • * 表示所有值。 例如:在分的字段上设置 *,表示每一分钟都会触发。
  • ? 表示不指定值。使用的场景为不需要关心当前设置这个字段的值。例如:要在每月的10号触发一个操作,但不关心是周几,所以需要周位置的那个字段设置为”?” 具体设置为 0 0 0 10 * ?
  • - 表示区间。例如 在小时上设置 “10-12”,表示 10,11,12点都会触发。
  • , 表示指定多个值,例如在周字段上设置 “MON,WED,FRI” 表示周一,周三和周五触发
  • / 用于递增触发。如在秒上面设置”5/15” 表示从5秒开始,每增15秒触发(5,20,35,50)。 在日字段上设置’1/3’所示每月1号开始,每隔三天触发一次。
  • L 表示最后的意思。在日字段设置上,表示当月的最后一天(依据当前月份,如果是二月还会依据是否是润年[leap]), 在周字段上表示星期六,相当于”7”或”SAT”。如果在”L”前加上数字,则表示该数据的最后一个。例如在周字段上设置”6L”这样的格式,则表示“本月最后一个星期五”
  • W 表示离指定日期的最近那个工作日(周一至周五). 例如在日字段上置”15W”,表示离每月15号最近的那个工作日触发。如果15号正好是周六,则找最近的周五(14号)触发, 如果15号是周未,则找最近的下周一(16号)触发.如果15号正好在工作日(周一至周五),则就在该天触发。如果指定格式为 “1W”,它则表示每月1号往后最近的工作日触发。如果1号正是周六,则将在3号下周一触发。(注,”W”前只能设置具体的数字,不允许区间”-“)。
  • # 序号(表示每月的第几个周几),例如在周字段上设置”6#3”表示在每月的第三个周六.注意如果指定”#5”,正好第五周没有周六,则不会触发该配置(用在母亲节和父亲节再合适不过了) ;小提示:’L’和 ‘W’可以一组合使用。如果在日字段上设置”LW”,则表示在本月的最后一个工作日触发;周字段的设置,若使用英文字母是不区分大小写的,即MON与mon相同。

示例

每隔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 * * ?

2. zone

时区,接收一个java.util.TimeZone#IDcron表达式会基于该时区解析。默认是一个空字符串,即取服务器所在地的时区。比如我们一般使用的时区Asia/Shanghai。该字段我们一般留空。

3. fixedDelay

上一次执行完毕时间点之后多长时间再执行。如:

 

@Scheduled(fixedDelay = 5000) //上一次执行完毕时间点之后5秒再执行

4. fixedDelayString

3. fixedDelay 意思相同,只是使用字符串的形式。唯一不同的是支持占位符。如:

 

@Scheduled(fixedDelayString = "5000") //上一次执行完毕时间点之后5秒再执行

占位符的使用(配置文件中有配置:time.fixedDelay=5000):

 

    @Scheduled(fixedDelayString = "${time.fixedDelay}")
    void testFixedDelayString() {
        System.out.println("Execute at " + System.currentTimeMillis());
    }

运行结果:

 

占位符的使用

5. fixedRate

上一次开始执行时间点之后多长时间再执行。如:

 

@Scheduled(fixedRate = 5000) //上一次开始执行时间点之后5秒再执行

6. fixedRateString

5. fixedRate 意思相同,只是使用字符串的形式。唯一不同的是支持占位符。

7. initialDelay

第一次延迟多长时间后再执行。如:

 

@Scheduled(initialDelay=1000, fixedRate=5000) //第一次延迟1秒后执行,之后按fixedRate的规则每5秒执行一次

8. initialDelayString

7. initialDelay 意思相同,只是使用字符串的形式。唯一不同的是支持占位符。

That's all ! Thanks for reading.

另外如果要想@Scheduled注解生效需要添加配置

package com.example.demo;

import lombok.extern.slf4j.Slf4j;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.aop.interceptor.SimpleAsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;

import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;


/**
 * 在用springboot框架做定时任务的时候,大部分情况都是直接通过@Scheduled注解来指定定时任务的。
 * 但是当你有多个定时任务时,@Scheduled并不一定会按时执行。
 * 因为使用@Scheduled的定时任务虽然是异步执行的,但是,默认不同的定时任务之间并不是并行的。
 *
 * 当未手动指定taskScheduler时,会通过Executors.newSingleThreadScheduledExecutor()创建默认的单线程线程池,
 * 且该线程池的拒绝策略为AbortPolicy,这种策略在线程池无可用线程时丢弃任务,
 * 并抛出异常RejectedExecutionException。
 *
 */
@Slf4j
@Configuration
@EnableScheduling
@EnableAsync
public class ScheduledConfig implements
        SchedulingConfigurer
//        , AsyncConfigurer
{


    /**
     * ThreadPoolTaskExecutor是一个专门用于执行任务的类。
     * ThreadPoolTaskScheduler是一个专门用于调度任务的类。
     * 一个ThreadPoolTaskExecutor通过它的corePoolSize , maxPoolSize , keepAliveSeconds和queueCapacity属性在线程池中提供细粒度的配置。
     * 诸如ThreadPoolTaskScheduler这样的调度器不提供这样的配置。
     */


    /** 最大线程数 */
    private static final int maxPoolSize = 10;
    /** 线程池名前缀 */
    private static final String threadNamePrefix = "yu-scheduled-";

    @Bean("asyncExecutorScheduled") // bean的名称,默认为首字母小写的方法名,如果不声明则会使用方法名
    public ThreadPoolTaskScheduler asyncExecutorScheduled(){
        ThreadPoolTaskScheduler executor = new ThreadPoolTaskScheduler();
        executor.setPoolSize(maxPoolSize);
        executor.setThreadNamePrefix(threadNamePrefix);
        executor.setAwaitTerminationSeconds(60);
        executor.setWaitForTasksToCompleteOnShutdown(true);
        // 初始化
        executor.initialize();
        return executor;
    }

    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        taskRegistrar.setTaskScheduler(this.asyncExecutorScheduled());
    }

//    /**
//     * 处理异步方法调用时要使用的实例
//     * @return
//     */
//    @Override
//    public Executor getAsyncExecutor() {
//        return this.asyncExecutorScheduled();
//    }
//
//    /**
//     * 在使用void返回类型的异步方法执行期间抛出异常时要使用的实例。
//     * @return
//     */
//    @Override
//    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
//        return new SimpleAsyncUncaughtExceptionHandler();
//    }
}

或者:

package com.example.demo;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;

import java.util.concurrent.ScheduledThreadPoolExecutor;


/**
 * scheduled 配置文件的第二种使用  不建议使用
 */
@Slf4j
@Configuration
@EnableScheduling
public class ScheduledConfig2 {



    @Bean
    public ScheduledThreadPoolExecutor scheduledExecutorService() {
        ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(10);
        return executor;
    }


}

实例:

package com.example.demo.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @Scehduled 定时任务测试
 */
@Slf4j
@Service
public class ScheduledService {
    /**5
     *测试
     */
    @Scheduled(cron = "*/5 * * * * *")
    public void testScheduled1(){
        log.info("定时1:{}",new Date());
    }

    @Scheduled(cron = "*/5 * * * * *")
    public void testScheduled2(){
        log.info("定时2:{}",new Date());
    }

}

结果:

2020-05-25 16:36:00.001  INFO 9116 --- [ yu-scheduled-1] c.example.demo.service.ScheduledService  : 定时2:Mon May 25 16:36:00 CST 2020
2020-05-25 16:36:00.005  INFO 9116 --- [ yu-scheduled-2] c.example.demo.service.ScheduledService  : 定时1:Mon May 25 16:36:00 CST 2020
2020-05-25 16:36:05.004  INFO 9116 --- [ yu-scheduled-1] c.example.demo.service.ScheduledService  : 定时2:Mon May 25 16:36:05 CST 2020
2020-05-25 16:36:05.004  INFO 9116 --- [ yu-scheduled-2] c.example.demo.service.ScheduledService  : 定时1:Mon May 25 16:36:05 CST 2020

参考自:https://www.jianshu.com/p/1defb0f22ed1

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章