在日常的开发中,我们常常回用到定时功能,目前简单一点的就是,Spring项目的Spring Task;然后复杂点的就是Quartz。
1. 简单的Spring Task
如果我们的项目中的定时任务,只是简单是在固定时间执行批量任务,就可以使用Spring Task来实现。
现在初始一个Spring boot项目,添加依赖:
<!-- Lombok 自动生成getter和setter等bean中方法 -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
相当简单的使用:
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
// 注入log
@Slf4j
@Component
// 开启注解定时任务的支持
@EnableScheduling
public class DemoTask {
// cron表达式
@Scheduled(cron = "0/1 * * * * *")
public void scheduled() throws Exception {
// 任务内容
log.info("=====>>>>> 开始定时任务 {}", System.currentTimeMillis());
Thread.sleep(2000);
System.out.println("完成定时任务");
}
}
然后开启项目,这样我们的一个定时任务就开始了:
2. cron表达式
cron表达式是用来描述一个定时任务的执行时间的,具体书写规则:
我也没理清,没得时间,我们可以去http://qqe2.com/cron/index手动配置即可,方便好用
3. 开启多线程的定时任务
1). 添加异步调用配置类
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.Executor;
// 异步调用配置,主要用于开启多线程的定时任务
@Configuration
@EnableAsync
public class AsyncConfig {
// 此处成员变量应该使用@Value从配置中读取
private int corePoolSize = 10;
private int maxPoolSize = 200;
private int queueCapacity = 10;
@Bean("taskAsync")
public Executor taskExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(corePoolSize);
executor.setMaxPoolSize(maxPoolSize);
executor.setQueueCapacity(queueCapacity);
executor.initialize();
return executor;
}
}
2). 在需要多线程的类或者方法上使用@Async开启多线程
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
// 注入log
@Slf4j
@Component
// 开启注解定时任务的支持
@EnableScheduling
public class DemoTask {
// cron表达式
@Async("taskAsync")
@Scheduled(cron = "0/1 * * * * *")
public void scheduled() throws Exception {
// 任务内容
log.info("=====>>>>> 开始定时任务 {}", System.currentTimeMillis());
Thread.sleep(2000);
System.out.println("完成定时任务");
}
}