How to timeout a Spring Boot @Scheduled Thread

我的未来我决定 提交于 2019-12-11 03:57:55

问题


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:


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 ...
  }
}


来源:https://stackoverflow.com/questions/31738755/how-to-timeout-a-spring-boot-scheduled-thread

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!