Spring Scheduled 定时任务 + 异步执行

Spring定时任务 + 异步执行

1.实现spring定时任务的执行

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;

@Component
public class ScheduledTasks {
    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd  HH:mm:ss");

    @Scheduled(fixedDelay = 5000)
    public void first() throws InterruptedException {
        System.out.println("第一个定时任务开始 : " + sdf.format(new Date()) + "\r\n线程 : " + Thread.currentThread().getName());
        System.out.println();
        Thread.sleep(1000 * 10); //模拟第一个任务执行的时间
    }

    @Scheduled(fixedDelay =3000)
    public void second() {
        System.out.println("第二个定时任务开始 : " + sdf.format(new Date()) + "\r\n线程 : " + Thread.currentThread().getName());
        System.out.println();
    }
}

由于执行定时任务默认的是单线程,存在的问题是:

​ 线程资源被第一个定时任务占用,第二个定时任务并不是3秒执行一次;

解决方法,创建定时任务的线程调度器,交给spring管理调度

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;

@Configuration
public class ScheduleConfig {

    @Bean
    public TaskScheduler taskScheduler() {
        ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
        scheduler.setPoolSize(10);
        return scheduler;
    }
}

这样就可以保证定时任务之间是多线程,而每个定时任务之间是单线程,保证了定时任务的异步,同时保证了消息的幂等性

posted @ 2020-06-18 14:33  Runtimeing  阅读(2829)  评论(0编辑  收藏  举报