Spring Scheduling注解介绍@Scheduled @EnableScheduling @Async @EnableAsync @Schedules

x33g5p2x  于2021-08-25 转载在 Spring  
字(2.1k)|赞(0)|评价(0)|浏览(1061)

在这篇快速文章中,Spring为任务调度和异步方法执行提供了注解支持,所以我们将探索**Spring调度注解。

让我们从org.springframework.scheduling.annotation包中探索任务调度和异步注解。

1. @Scheduled注解

@Scheduled注解与一些关于何时执行的信息一起被添加到一个方法中,Spring会处理剩下的事情。

例如,下面这个方法将每隔5秒被调用一次,并有固定的延迟,也就是说,这个时间段将从前面每次调用的完成时间开始计算。

@Scheduled(fixedDelay=5000)
public void doSomething() {
    // something that should execute periodically
}

如果需要固定速率的执行,只需改变注解中指定的属性名称。以下内容将在每次调用的连续开始时间之间每5秒执行一次。

@Scheduled(fixedRate=5000)
public void doSomething() {
    // something that should execute periodically
}

对于固定延迟和固定速率的任务,可以指定一个初始延迟,表明在第一次执行该方法之前要等待的毫秒数。

@Scheduled(initialDelay=1000, fixedRate=5000)
public void doSomething() {
    // something that should execute periodically
}

如果简单的周期性调度没有足够的表现力,那么可以提供一个cron表达式。例如,下面的内容将只在工作日执行。

@Scheduled(cron="/*/5 /* /* /* /* MON-FRI")
public void doSomething() {
    // something that should execute on weekdays only
}

2. @EnableScheduling 注解

@EnableScheduling 注解用于在应用程序中启用调度。我们还必须把它与@Configuration结合起来使用。

@Configuration
@EnableScheduling
public class Appconfig{}

因此,我们现在可以用@Scheduled定期运行方法。

3. @Async注解

@Async注解可以提供给一个方法,这样该方法的调用将以异步方式发生。换句话说,调用者将在调用后立即返回,而方法的实际执行将发生在一个已经提交给Spring TaskExecutor的任务中。在最简单的情况下,该注解可以应用于一个无效返回的方法。

@Async
void doSomething() {
    // this will be executed asynchronously
}

与带有 @Scheduled 注解的方法不同,这些方法可以期待参数,因为它们将在运行时被调用者以 "正常 "方式调用,而不是从容器管理的预定任务中调用。 

例如,下面是@Async注解的合法应用。

@Async
void doSomething(String s) {
    // this will be executed asynchronously
}

即使是返回值的方法也可以被异步地调用。然而,这种方法需要有一个Future类型的返回值。这仍然提供了异步执行的好处,因此调用者可以在调用Future的get()之前执行其他任务。

@Async
Future<String> returnSomething(int i) {
    // this will be executed asynchronously
}

@Async不能与生命周期回调(如[$7$])一起使用。要异步初始化Spring Bean,你目前必须使用一个单独的初始化Spring Bean来调用目标上的@Async注解方法,然后。

public class SampleBeanImpl implements SampleBean {
    @Async
    void doSomething() {
        // ...
    }
}

public class SampleBeanInitializer {

    private final SampleBean bean;

    public SampleBeanInitializer(SampleBean bean) {
        this.bean = bean;
    }

    @PostConstruct
    public void initialize() {
        bean.doSomething();
    }
}

4. @EnableAsync注解

通过这个注解,我们可以在Spring中启用异步功能。我们必须和@Configuration一起使用它。

@Configuration
@EnableAsync
public class AppConfig{}

现在,我们启用了异步调用,我们可以使用@Async来定义支持它的方法。

5. @Schedules注解

我们可以使用这个注解来指定多个@Scheduled规则。

@Schedules({ 
  @Scheduled(fixedRate = 10000), 
  @Scheduled(cron = "0 /* /* /* /* MON-FRI")
})
void checkVehicle() {
    // ...
}

相关文章

微信公众号

最新文章

更多