ScheduledThreadPoolExecutor和@Scheduled区别

ScheduledThreadPoolExecutor:https://blog.csdn.net/mumuwang1234/article/details/119153582

@Scheduled:https://blog.csdn.net/mumuwang1234/article/details/118442792

一.问题背景

最近在看ScheduledThreadPoolExecutor执行定时任务的使用,突然想起来前段时间学习了注解@Scheduled也是可以做定时任务的,那这两者到底什么区别呢?

二.区别

废话不多说,直接上代码吧

ScheduledThreadPoolExecutor代码:

public class TheadExectorTest {
    public static void main(String[] args){
        ThreadFactory delayNotifyThreadFactory = ThreadFactoryBuilder.create().setNamePrefix("delayScheduledThread-").build();
        ScheduledThreadPoolExecutor delayNotifyExecutor = new ScheduledThreadPoolExecutor(100, delayNotifyThreadFactory);
        delayNotifyExecutor.scheduleAtFixedRate(()->System.out.println(System.currentTimeMillis()+"xiaozhou"), 1,200,TimeUnit.MILLISECONDS);
    }
}

@Scheduled代码:

@Component
@EnableScheduling
public class ScheduledTask {
    @Scheduled(fixedDelay = 5000)
    public void reportName(){

        System.out.println(System.currentTimeMillis()+"xiaozhou");
    }
}

三.总结

@Scheduled是单线程或多线程,定时执行,可延迟,周期性执行任务,且可以设置 cron,更灵活一点

ScheduledThreadPoolExecutor类,适用于多个后台线程执行任务,可延迟,可周期性执行任务或非周期性(主要是调用的方法),但是时间上基本固定

上一篇:springboot使用@Scheduled之cron表达式详解


下一篇:SpringBoot之scheduled定时器