Spring Task 实现定时推送消息
项目中需要执行一些定时任务,比如在凌晨时候更新一些新的信息,每天上午10:30定时发送消息通知等等
- 导入相关依赖
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
- 创建定时任务
@Slf4j
@Component
public class ScheduledService {
@Async
@Scheduled(cron = " 0 30 10 ? * 1,2,3,4,5") //周一到周五每天上午10:30
public void scheduled(){
//定时任务
System.out.println("=====>>>>>使用cron {}"+System.currentTimeMillis());
}
@Scheduled(fixedRate = 5000) //毫秒
public void scheduled1() {
System.out.println("=====>>>>>使用fixedRate{}"+System.currentTimeMillis());
}
@Scheduled(fixedDelay = 5000) //毫秒
public void scheduled2() {
System.out.println("=====>>>>>fixedDelay{}"+System.currentTimeMillis());
}
}
主类使用@EnableScheduling注解开启对定时任务的支持,然后启动项目
执行时间的配置
在方法上使用@Scheduled注解来设置任务的执行时间,并且使用三种属性配置方式:
- fixedRate:定义一个按一定频率执行的定时任务
- fixedDelay:定义一个按一定频率执行的定时任务,与上面不同的是,改属性可以配合initialDelay, 定义该任务延迟执行时间。
- cron:通过表达式来配置任务执行时间
cron表达式详解
一个cron表达式有至少6个(也可能7个)有空格分隔的时间元素。按顺序依次为:
1. 秒(0~59)
2. 分钟(0~59)
3. 小时(0~23)
4. 天(0~31)
5. 月(0~11)
6. 星期(1~7 1=SUN 或 SUN,MON,TUE,WED,THU,FRI,SAT)
7. 年份(1970-2099)
在线cron表达式生成:http://qqe2.com/cron/index
问题
当运行一个定时任务是并没有什么问题, 但是当多线程并发执行, 如果其中一个任务出现问题, 会导致其他任务也无法正常运行
解决办法(多线程执行)
使用config配置类的方式添加配置
@Configuration
@EnableAsync
public class AsyncConfig {
/*
此处成员变量应该使用@Value从配置中读取
*/
private int corePoolSize = 10;
private int maxPoolSize = 200;
private int queueCapacity = 10;
@Bean
public Executor taskExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(corePoolSize);
executor.setMaxPoolSize(maxPoolSize);
executor.setQueueCapacity(queueCapacity);
executor.initialize();
return executor;
}
}
@Configuration:表明该类是一个配置类
@EnableAsync:开启异步事件的支持
然后在定时任务的类或者方法上添加@Async 。最后重启项目,每一个任务都是在不同的线程中