定时任务的实现
@Scheduled注解
简介
注解@Scheduled 可以作为一个触发源添加到一个方法中,例如,以下的方法将以一个固定延迟时间5秒钟调用一次执行,这个周期是以上一个调用任务的完成时间为基准,在上一个任务完成之后,5s后再次执行:
如果需要以固定速率执行,只要将注解中指定的属性名称改成fixedRate即可,以下方法将以一个固定速率5s来调用一次执行,这个周期是以上一个任务开始时间为基准,从上一任务开始执行后5s再次调用:
如果简单的定期调度不能满足,那么cron表达式提供了可能。例如,下面的方法将只会在工作日执行:
还可以通过使用zone属性来指定cron表达式被调用的时区。
注意:
1、spring的注解@Scheduled 需要写在实现方法上;
2、定时器的任务方法不能有返回值(如果有返回值,spring初始化的时候会告诉你有个错误、需要设定一个proxytargetclass的某个值为true),不能指向任何的参数;
3、如果该方法需要与应用程序上下文的其他对象进行交互,通常是通过依赖注入来实现;
4、实现类上要有组件的注解@Component。
@Scheduled参数详解
-
corn:
该参数接受一个corn表达式,该表达式是一个字符串,字符串以5或者6个空格隔开,分成6,7个域,每个域代表一个含义。
语法为【秒】【分】【时】【日】【月】【周】【年】,其中年可省略
-
通配符说明:
符号 | 描述 |
---|---|
* | 表示所有值。 例如:在分的字段上设置 *,表示每一分钟都会触发。 |
? | 表示不指定值。使用的场景为不需要关心当前设置这个字段的值。例如:要在每月的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相同。 |
-
zone
时区,接收一个java.util.TimeZone#ID。cron表达式会基于该时区解析。默认是一个空字符串,即取服务器所在地的时区。比如我们一般使用的时区Asia/Shanghai。该字段我们一般留空。 -
fixedDelay
上一次执行完毕时间点之后多长时间再执行。如:
-
fixedDelayString
与 3. fixedDelay 意思相同,只是使用字符串的形式。唯一不同的是支持占位符。如:
占位符的使用(配置文件中有配置:time.fixedDelay=5000):
-
fixedRate
上一次开始执行时间点之后多长时间再执行。如:
-
fixedRateString
与 5. fixedRate 意思相同,只是使用字符串的形式。唯一不同的是支持占位符。 -
initialDelay
第一次延迟多长时间后再执行。如:
@Scheduled(initialDelay=1000, fixedRate=5000) //第一次延迟1秒后执行,之后按fixedRate的规则每5秒执行一次 -
initialDelayString
与 8. initialDelayString 意思相同,只是使用字符串的形式。唯一不同的是支持占位符。
完整例子
package com.phy.biz.category.work;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.util.List;
/**
* @author :xp
* @date :Created in 2019/1/25 10:09
*/
@Component(ListWork.BEAN_NAME)
@EnableScheduling
@Slf4j
public class ListWork {
static final String BEAN_NAME = "biz.category.work.ListWork";
private ProductCategoryService productCategoryService;
public ListWork(ProductCategoryService productCategoryService) {
this.productCategoryService = productCategoryService;
}
@Scheduled(fixedDelay = 30 *1000)
public void List(){
log.info("自己设置定时任务开始");
System.out.println("定时任务开始执行!!!");
}
}
Spring定时任务并行(异步)处理
在SpringBoot中设置了定时任务之后 , 在某个点总是没有执行 . 经过搜索研究发现 , spring 定时器任务scheduled-tasks默认配置是单线程串行执行的 . 即在当前时间点之内 . 如果同时有两个定时任务需要执行的时候 , 排在第二个的任务就必须等待第一个任务执行完毕执行才能正常运行.如果第一个任务耗时较久的话 , 就会造成第二个任务不能及时执行 . 这样就可能由于时效性造成其他问题 . 而在实际项目中 , 我们也往往需要这些定时任务是"各干各的" , 而不是排队执行.
方法一
package com.phy.biz.category;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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.ThreadPoolTaskScheduler;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import java.lang.reflect.Method;
import java.util.concurrent.Executor;
/**
* @author :xp
* @date :Created in 2019/3/29 15:19
* @description:AsyncSchedulingConfig
* 将此配置类,放在项目的运行的BizApplication 启动类下
*/
@Configuration(AsyncSchedulingConfig.BEAN_NAME)
@EnableScheduling
@EnableAsync
public class AsyncSchedulingConfig implements SchedulingConfigurer, AsyncConfigurer{
static final String BEAN_NAME = "biz.config.AsyncSchedulingConfig";
/**
* 并行任务
*/
public void configureTasks(ScheduledTaskRegistrar taskRegistrar)
{
TaskScheduler taskScheduler = taskScheduler();
taskRegistrar.setTaskScheduler(taskScheduler);
}
/**
* 并行任务使用策略:多线程处理(配置线程数等)
*
* @return ThreadPoolTaskScheduler 线程池
*/
@Bean(destroyMethod = "shutdown")
public ThreadPoolTaskScheduler taskScheduler()
{
ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
scheduler.setPoolSize(20);//设置线程池的大小
scheduler.setThreadNamePrefix("task-"); //设置线程名开头
scheduler.setAwaitTerminationSeconds(60);//设置终止等待毫秒数
scheduler.setWaitForTasksToCompleteOnShutdown(true);//设置等待任务在关机时完成
return scheduler;
}
/**
* 异步任务
*/
public Executor getAsyncExecutor()
{
Executor executor = taskScheduler();
return executor;
}
/**
* 异步任务中的异常处理
*/
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler()
{
return new SimpleAsyncUncaughtExceptionHandler(){
private final Logger logger = LoggerFactory.getLogger(getClass());
@Override
public void handleUncaughtException(Throwable ex, Method method, Object... params) {
logger.error("Uncaught Async Exception", ex);
}
};
}
}
方案二
package com.phy.biz.category;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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.ThreadPoolExecutorFactoryBean;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import java.lang.reflect.Method;
import java.util.concurrent.Executor;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadPoolExecutor;
/**
* @author :xp
* @date :Created in 2019/3/29 15:19
* @description:
*/
@Configuration(AsyncSchedulingConfig.BEAN_NAME)
@EnableScheduling
@EnableAsync
public class AsyncSchedulingConfig implements SchedulingConfigurer, AsyncConfigurer{
static final String BEAN_NAME = "biz.config.AsyncSchedulingConfig";
/**
* 并行任务
*/
@Bean
public ThreadPoolExecutorFactoryBean executorFactory() {
ThreadPoolExecutorFactoryBean factoryBean = new ThreadPoolExecutorFactoryBean();
factoryBean.setThreadNamePrefix("task-biz-");
factoryBean.setCorePoolSize(10);
factoryBean.setMaxPoolSize(25);
factoryBean.setQueueCapacity(50);
factoryBean.setKeepAliveSeconds(120);
factoryBean.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
return factoryBean;
}
/**
* 并行任务使用策略:多线程处理(配置线程数等)
*
* @return ThreadPoolTaskScheduler 线程池
*/
@Override
public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
taskRegistrar.setScheduler(new ScheduledThreadPoolExecutor(10, executorFactory()));
}
/**
* 异步任务
*/
public Executor getAsyncExecutor()
{
return executorFactory().getObject();
}
/**
* 异步任务中的异常处理
*/
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler()
{
return new SimpleAsyncUncaughtExceptionHandler(){
private final Logger logger = LoggerFactory.getLogger(getClass());
@Override
public void handleUncaughtException(Throwable ex, Method method, Object... params) {
logger.error("Uncaught Async Exception", ex);
}
};
}
}