通话后几秒钟/几分钟/几小时运行任务

时间:2018-12-03 17:06:14

标签: java spring-boot concurrency task scheduled-tasks

Spring Boot可以在通话后几分钟后运行任务吗?

更新: 发现Spring Boot具有ThreadPoolTaskScheduler。这样可以实现具有时间延迟的一次任务执行。请参阅下面的答案

1 个答案:

答案 0 :(得分:0)

首先,我们需要定义一个Bean

@Bean
public ThreadPoolTaskScheduler getScheduler(){
    ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
    scheduler.setPoolSize(10);
    return scheduler;
}

需要执行的任务

public class WakeUpCallTask implements Runnable {

    private String parameter1;

    private String parameter2;

    public WakeUpCallTask(String parameter1, String parameter2) {
        super();
        this.parameter1= parameter1;
        this.parameter2= parameter2;
    }

    @Override
    public void run() {
        // Code that should be executed
    }

}

端点示例-在10000毫秒内安排任务

@Autowired
ThreadPoolTaskScheduler scheduler;

@PostMapping(value = "/wake-me-up", consumes = "application/json")
@ResponseStatus(HttpStatus.OK)
public void scheduleCall(@RequestBody WakeMeUpRequest request) {
    scheduler.schedule(
            new WakeUpCallTask(request.getParameter1(), request.getParameter2()),
            new Date(System.currentTimeMillis() + 10000));
}