如何使Spring Boot @Scheduled线程超时 [英] How to timeout a Spring Boot @Scheduled Thread

查看:1358
本文介绍了如何使Spring Boot @Scheduled线程超时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Spring Boot应用程序,该应用程序在一天的特定时间运行许多作业(由CRON配置). 现在,我发现该应用程序正在运行,但是预定的作业没有得到执行. 有什么方法可以在Spring中用@Scheduled注释的任务中添加超时.

I have a Spring Boot application which runs a number of jobs at specific times of the day (configured by CRON). Now I find that the the application is running but the scheduled jobs are not getting executed. Is there any way to add a timeout to a task annotated with @Scheduled in Spring.

这样,即使作业被阻塞或等待,也可以将其杀死,从而使其他线程得以顺利执行.线程可以等待指定的时间,然后如果任务尚未完成,请终止线程.

So that even if the job is blocked or waiting, it can be killed, so that the other threads are allowed to execute smoothly. The thread can wait for a specified time and then if the task has not completed, kill the thread.

我知道我可以使用以下方法来增加池大小:

I know I can increase the poolsize using:

Executors.newScheduledThreadPool();

Executors.newScheduledThreadPool();

但是如果最终所有线程都被阻塞,会发生什么情况

But what happens if eventually all threads are blocked

我浏览了整个论坛,看到了使用FutureTasks提及的解决方案.可以将其应用于带有@Scheduled批注的任务吗? 由于该应用程序是春季启动的,因此也没有用于配置超时的xml配置.

I have looked through the forum, and saw solutions which mentioned using FutureTasks. Can this be applied to a task with @Scheduled annotation? Since the application is spring-boot there is no xml configuration either to configure a timeout.

推荐答案

您可以使用TaskScheduler来启动和控制任务.在您的@Configuration类中:

You can use TaskScheduler to start and control tasks. In your @Configuration class:

@Configuration
public class YourConfig {

  @Bean
  public TaskScheduler scheduler() {
    return new ThreadPoolTaskScheduler();
  }
  // ...

然后,您可以通过以下方式安排任务:

After then, you can schedule your task in this way:

@Service
public class YourTaskRunnable implements Runnable {

  @Autowired
  private TaskScheduler scheduler;

  @PostConstruct
  private void init() {
    ScheduledFuture future = this.scheduler.schedule(this, /* to execute immediately, for example */ Calendar.getInstance().getTime());
    // ...
  }


  @Override
  public void run() {
  // Your task code ...
  }
}

这篇关于如何使Spring Boot @Scheduled线程超时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆