admin管理员组

文章数量:1130349

在项目过程中经常会用到spring的Schedule定时任务
然后Schedule定时任务默认是单线程的,在项目过程中就会出现比较耗时的任务跟比较频繁的任务冲突问题,

单线程情况下,例如8:00有一个耗时大约10分钟的定时任务,还有一个每一分钟一次的定时任务,那么8:00任务开始时,一分钟的任务就已经进入排队序列,并不执行

故而需要配置多线程的定时任务配置

配置文件:
ScheduleConfig.java

package com.snimay.business.job;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;

import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

/**
 * @author kongzhiqiang
 * @Description
 * @Date 2021/8/26 14:34
 */
@Configuration
@EnableScheduling
public class ScheduleConfig implements SchedulingConfigurer {

    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
    	//注册最大线程池100
        taskRegistrar.setScheduler(Executors.newScheduledThreadPool(100));
    }

}

定时任务实现类

/**
	 * Description: -----
	 *
	 * @throws Exception
	 * @interfaceName
	 * @author kongzhiqiang
	 */
	@Async
	@Scheduled(cron = "0 0/1 * * * ? ")
	public void scheduledBatchOrderCheckPrice() throws Exception {
		//dosomting...
	}

@Async 异步执行
被@Async标注过的方法不是在主线程中执行,是另开了一个线程,并且进行调度,从打印就可以看出,调度是随机的!

@Scheduled(fixedDelay = 1000)
被@Scheduled标注过的函数会按照配置的运行方式自动执行!此处配置的是fixedDelay=1000含义是每隔1000ms执行一次(在上次执行完后开始计时1000ms)

既然涉及到异步,就涉及到线程池有多大?队列有多大?

在项目过程中经常会用到spring的Schedule定时任务
然后Schedule定时任务默认是单线程的,在项目过程中就会出现比较耗时的任务跟比较频繁的任务冲突问题,

单线程情况下,例如8:00有一个耗时大约10分钟的定时任务,还有一个每一分钟一次的定时任务,那么8:00任务开始时,一分钟的任务就已经进入排队序列,并不执行

故而需要配置多线程的定时任务配置

配置文件:
ScheduleConfig.java

package com.snimay.business.job;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;

import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

/**
 * @author kongzhiqiang
 * @Description
 * @Date 2021/8/26 14:34
 */
@Configuration
@EnableScheduling
public class ScheduleConfig implements SchedulingConfigurer {

    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
    	//注册最大线程池100
        taskRegistrar.setScheduler(Executors.newScheduledThreadPool(100));
    }

}

定时任务实现类

/**
	 * Description: -----
	 *
	 * @throws Exception
	 * @interfaceName
	 * @author kongzhiqiang
	 */
	@Async
	@Scheduled(cron = "0 0/1 * * * ? ")
	public void scheduledBatchOrderCheckPrice() throws Exception {
		//dosomting...
	}

@Async 异步执行
被@Async标注过的方法不是在主线程中执行,是另开了一个线程,并且进行调度,从打印就可以看出,调度是随机的!

@Scheduled(fixedDelay = 1000)
被@Scheduled标注过的函数会按照配置的运行方式自动执行!此处配置的是fixedDelay=1000含义是每隔1000ms执行一次(在上次执行完后开始计时1000ms)

既然涉及到异步,就涉及到线程池有多大?队列有多大?

本文标签: 多线程schedule