【问题标题】:Long running spring scheduled task长时间运行的春季计划任务
【发布时间】:2019-05-18 22:17:18
【问题描述】:

我在 context.xml 文件中定义了一个 Spring 计划任务,它每分钟运行一次。 该任务调用一个 postgres 存储过程。 存储过程运行时间可以持续一分钟以上。 如果当前运行未完成,spring 框架会调用相同的调度程序吗? 谢谢,

【问题讨论】:

    标签: java spring scheduled-tasks


    【解决方案1】:

    在spring框架中,一个定时任务只能由一个线程执行,如果执行时间长于间隔时间,任务就会被延迟。下面是一个简单的例子:

    @Scheduled(cron = "0/3 * * * * *")
    public void work() {
        log.info("begin to do some work,current thread is {}", Thread.currentThread().getName());
        try {
            TimeUnit.SECONDS.sleep(5);
        } catch (InterruptedException e) {
            log.error(e.toString());
        }
    }
    

    我创建了一个定时任务,预期执行顺序:0 3 6 9 ...,但是任务需要更多时间,所以执行顺序:0 6 12 18 ...

    spring 中所有的任务都会在线程上执行(默认),为了减少任务之间的干扰,我们可以支持一个线程池来执行这样的调度任务:

    @Bean
    public ThreadPoolTaskScheduler taskExecutor() {
        ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
        scheduler.setPoolSize(20);
        return scheduler;
    }
    

    其他关于春季计划任务的问题:Does spring @Scheduled annotated methods runs on different threads?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-03-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-23
      • 2018-02-28
      • 2018-05-06
      相关资源
      最近更新 更多