How to timeout a Spring Boot @Scheduled Thread

2019-07-13 10:05发布

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();

But what happens if eventually all threads are blocked

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.

1条回答
疯言疯语
2楼-- · 2019-07-13 10:58

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 ...
  }
}
查看更多
登录 后发表回答