无论有多少个定时任务,都是由一个线程来管理。
验证办法:
如果是一个线程,不同的schedule之间会等待。 如果是多个线程,不同的schedule之间不会等待。

如下代码说明用法:

@SpringBootApplication
@EnableScheduling
public class AccessingDataMysqlApplication {
    public static void main(String[] args) {
        ApplicationContext app = SpringApplication.run(AccessingDataMysqlApplication.class, args);

    }
    @Scheduled(cron = "0/2 * * * * ?")
    public void schedule1(){
        try {
            System.out.println(Thread.currentThread().getName()+", 1 "+Instant.now());
            Thread.sleep(5000);
            System.out.println(Thread.currentThread().getName()+" 1 end");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    @Scheduled(cron = "0/2 * * * * ?")
    public void schedule2(){
        try {
            System.out.println(Thread.currentThread().getName()+", 2  "+ Instant.now());
            Thread.sleep(5000);
            System.out.println(Thread.currentThread().getName()+" 2  end");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

输出为:

pool-1-thread-1, 2  2020-02-08T14:21:46.001Z
pool-1-thread-1 2  end
pool-1-thread-1, 1 2020-02-08T14:21:51.002Z
pool-1-thread-1 1 end
pool-1-thread-1, 2  2020-02-08T14:21:56.002Z
pool-1-thread-1 2  end
pool-1-thread-1, 1 2020-02-08T14:22:01.003Z
pool-1-thread-1 1 end
pool-1-thread-1, 2  2020-02-08T14:22:06.076Z

如果是多线程,同序号线程应该5秒输出一次。
但是发现都收到影响了,所以定时任务是一个线程管理的。

定时任务中如何避免阻塞

定时任务往往被用于批量执行操作。 这里要注意定时任务是单线程的。 如果某个出现问题,后续的就无法继续执行。
方案:
对for循环中的每一条记录,单独进行try catch。使没一条数据都是独立的。 这样一条错误,不影响后续执行。

另外,如果某条错误记录被多次重复执行,会连续打印很多相同的错误日志。 这个可以加个重试字段来标记。

schedule定时任务还有考虑集群问题

例如2台机器,部署相同应用,如果不考虑调度,可能会将相同逻辑执行2遍,造成资源浪费甚至是错误数据。
所以集群中使用schedule任务一定要注意。

更多推荐

springboot中schedule定时任务是一个线程管理的么