- spring的@Scheduled定时任务默认是单线程,多个任务执行起来时间会有问题:B任务会因为A任务执行起来需要20S而被延后20S执行。
- springmvc配置定时任务为多线程只需要两步,配置文件修改如下配置:
<!-- 配置执行器 -->
task:executor/@pool-size:可以指定执行线程池的初始大小、最大大小 .
task:executor/@queue-capacity:等待执行的任务队列的容量
task:executor/@rejection-policy:当等待队列爆了时的策略,分为丢弃、由任务执行器直接运行等方式
<task:executor id="executor" keep-alive="3600" pool-size="100-200" queue-capacity="500" rejection- policy="CALLER_RUNS" />
<!-- 配置任务线程池 -->
<task:scheduler id="schedulerTest" pool-size="10" />
<!-- 启用annotation方式 -->
<task:annotation-driven scheduler="schedulerTest" executor="executor"/>
- springboot配置定时任务为多线程如下:
-
开启缓存注解
@SpringBootApplication
@EnableScheduling //开启定时任务
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
-
配置多线程
@Configuration
public class ScheduleConfig implements SchedulingConfigurer {
@Override
public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
taskRegistrar.setScheduler(Executors.newScheduledThreadPool(10));
}
}
- 编写定时任务
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component
public class CustomerLevelTest {
@Scheduled(cron="0/5 * * * * ? ") //每5秒执行一次
public void testCron() {
DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.err.println (Thread.currentThread ().getName ()+"="+sdf.format(new Date())+"*********每5秒执行一次");
}
@Scheduled(cron="0/4 * * * * ? ") //每5秒执行一次
public void testCron4() {
DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.err.println (Thread.currentThread ().getName ()+"="+sdf.format(new Date())+"*********每4秒执行一次");
}
}