spring boot 定时任务多线程
1. 单线程
@Component
public class SchedulingTask
{
Logger logger = LoggerFactory.getLogger(SchedulingTask.class);
@Scheduled(cron = "0/2 * * * * ?")
public void action2()
{
logger.info("Drink water -------------------------------------");
}
@Scheduled(cron ="0/3 * * * * ?")
public void action3(){
logger.info("eat biscuits===================================================");
}
@Scheduled(cron = "15 * * * * ?")
public void action1() {
logger.info("play football --start------");
List<String> list = new ArrayList<>();
for(int i=0; i<100; i++){
list.add(String.valueOf(100+i));
}
list.parallelStream().forEach(str -> {
if(0 == Integer.parseInt(str)%10)
logger.info("play football goal={}",str);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
});
logger.info("play football --end--------");
}
}
2. 多线程
@Configuration
@EnableScheduling
public class SchedulingConfig implements SchedulingConfigurer
{
@Override
public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
taskRegistrar.setScheduler(Executors.newScheduledThreadPool(10));
}
}
spring 定时任务多线程
1. 多线程
<beans>
<task:annotation-driven scheduler="taskScheduler"/>
<task:scheduler id="taskScheduler" pool-size="42"/>
<task:scheduled-tasks scheduler="taskScheduler">
<task:scheduled ref="myTask" method="work" fixed-rate="1000"/>
</task:scheduled-tasks>
<bean id="myTask" class="com.foo.MyTask"/>
</beans>
注:
- @EnableScheduling:启用定时任务(启用Spring的计划任务执行能力);
- @Scheduled:创建定时任务,标注一个定时任务方法;
- Cron表达式生成器:http://cron.qqe2.com/