简体   繁体   English

如何使用 Spring 延迟计划任务?

[英]How to delay a scheduled task with Spring?

I'd like to create a method that delays the execution on method invocation by 60s.我想创建一个方法,将方法调用的执行延迟 60 秒。

Problem: if the method is called within that 60s, I want it to be delayed again by 60s from last point of invocation.问题:如果在 60 秒内调用该方法,我希望它从调用的最后一个点再次延迟 60 秒。 If then not called within 60s, the execution may continue.如果在 60 秒内未调用,则可以继续执行。

I started as follows, but of course this is only a one-time delay:我是这样开始的,但是当然这只是一次延迟:

public void sendDelayed(String info) {
   //TODO create a task is delayed by +60s for each method invocation 
   ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
   executorService.schedule(Classname::someTask, 60, TimeUnit.SECONDS);
}

How could I further delay the execution on each invocation?我怎样才能进一步延迟每次调用的执行?

executorService.schedule returns a ScheduledFuture which provides a cancel method to cancel its execution. executorService.schedule返回一个ScheduledFuture ,它提供了一个cancel方法来取消其执行。 cancel takes a single boolean parameter mayInterruptIfRunning which, when set to false , will only cancel the execution if the task has not started yet. cancel采用单个 boolean 参数mayInterruptIfRunning ,当设置为false时,仅当任务尚未开始时才会取消执行。 See also the docs .另请参阅文档

Using this you could do something like this:使用它你可以做这样的事情:

private ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();

private ScheduledFuture<?> future;

public void sendDelayed(String info) {
    // When there is a task that has not been started yet, stop it:
    if (future != null) {
        boolean cancelled = future.cancel(false);
        if (cancelled) {
            logger.debug("Task has been cancelled before execution");
        } else {
            logger.debug("Task is already running or has been completed");
        }
    }

    // Old task has been cancelled or already started - schedule a new task
    future = executorService.schedule(Classname::someTask, 60, TimeUnit.SECONDS);
}

You may have to take care of avoiding race conditions regarding concurrent access to the future field though.不过,您可能必须注意避免有关对future字段的并发访问的竞争条件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM