配置spring定时任务

配置spring定时任务

参考项目

https://github.com/wenming5112/spring-ssm-example

定时任务依赖

<!-- 定时任务 -->
<dependency>
    <groupId>org.quartz-scheduler</groupId>
    <artifactId>quartz</artifactId>
    <version>2.2.3</version>
</dependency>

注解方式配置线程池

// 启动异步调用
@EnableAsync 
public class AsyncApplicationWithAnnotation {
 
    /**
     * 自定义异步线程池
     */
 
    @Bean(name = "asyncTaskExecutor")
    public AsyncTaskExecutor taskExecutor() { 
 
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setThreadNamePrefix("Anno-Executor");
        executor.setMaxPoolSize(10);
        executor.setCorePoolSize(3);
        executor.setQueueCapacity(100);
        // 设置自定义拒绝策略
        // executor.setRejectedExecutionHandler(new RejectedExecutionHandler() {
        //     @Override
        //     public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
        //         // .....
        //         // 也可以使用默认的拒绝策略,在spring中指定策略名称
        //     }
        // });
        // 使用默认的拒绝策略,有四种
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        //等待所有任务调度完成在关闭线程池,保证所有的任务被正确处理
        executor.setWaitForTasksToCompleteOnShutdown(true);
        //线程池关闭时等待其他任务的时间,不能无限等待,确保应用最后能被关闭。而不是无限期阻塞
        executor.setAwaitTerminationSeconds(60);
        //线程池初始化
        executor.initialize();
        return executor; 
    }
 
}

xml配置线程池和定时任务

在spring.xml中配置

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:task="http://www.springframework.org/schema/task"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/task
       http://www.springframework.org/schema/task/spring-task-3.0.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context-3.0.xsd">

<!-- 扫描定时任务所在的包 -->
<context:component-scan base-package="com.jd.task.demo"/>

<!-- 此方式等价于 @EnableAsync, executor指定线程池 -->
<task:annotation-driven executor="xmlExecutor"/>

<!-- id指定线程池产生线程名称的前缀 -->
<task:executor id="xmlExecutor" pool-size="5-25"
    queue-capacity="100"
    keep-alive="120"
    rejection-policy="CALLER_RUNS"/>

拒绝策略

  • ThreadPoolExecutor.AbortPolicy:丢弃任务并抛出RejectedExecutionException异常。
  • ThreadPoolExecutor.DiscardPolicy:也是丢弃任务,但是不抛出异常。
  • ThreadPoolExecutor.DiscardOldestPolicy:丢弃队列最前面的任务,然后重新尝试执行任务(重复此过程)
  • ThreadPoolExecutor.CallerRunsPolicy:由调用线程处理该任务

编写异步任务


@Component
@EnableScheduling
public class ScheduledTaskExample {
 
    public ScheduledTaskExample(){
    }
 
    @Async("asyncTaskExecutor")
    @Scheduled(cron = "0/2 * * * * ?")
    //@Scheduled(fixedRate = 1000) //一秒执行一次
    public void example(){
       System.out.println("执行异步任务...");
    }

    @Async()
    @Scheduled(cron = "0/1 * * * * ?")
    //@Scheduled(fixedRate = 1000) //一秒执行一次
    public void example(){
       System.out.println("执行异步任务...");
    }
}

全局线程池

@Async()注解不指定线程池时默认使用全局线程池

@EnableAsync
@Configuration
public class AsyncGlobalConfig extends AsyncConfigurerSupport {
    private static final String THREAD_PREFIX = "defineGlobalAsync-";

    @Override
    public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setThreadNamePrefix(THREAD_PREFIX);
        executor.setCorePoolSize(3);
        executor.setMaxPoolSize(10);
        executor.setQueueCapacity(100);
        executor.setKeepAliveSeconds(60);
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        executor.setWaitForTasksToCompleteOnShutdown(true);
        executor.setAwaitTerminationSeconds(60);
        executor.initialize();
        return executor;
    }

    //使用自定义异常处理
    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return new CustomAsyncExceptionHandler();
    }
}

class CustomAsyncExceptionHandler implements AsyncUncaughtExceptionHandler {

        @Override
        public void handleUncaughtException(Throwable e, Method method, Object... args) {
            //处理异常
        }
}

posted @ 2022-04-05 19:59  itwetouch  阅读(295)  评论(0编辑  收藏  举报