0

GIỚI THIỆU SCHEDULE TRONG SPRING

1- Spring @Scheduled Annotation Đôi khi trong một ứng dụng bạn cần phải tạo ra một tác vụ theo lịch trình để chạy nền. Ví dụ: tạo các tệp sơ đồ trang web, gửi email định kỳ, ... @ Scheduled là một chú thích sử dụng để cấu hình một lịch trình, nó được chú thích trên một method, và method này sẽ được chạy theo lịch trình được cấu hình bởi @ Được lên lịch. @Scheduled

@ Scheduled public @interface Scheduled {

String cron() default "";

String zone() default "";

long fixedDelay() default -1;

String fixedDelayString() default "";

long fixedRate() default -1;

String fixedRateString() default "";

long initialDelay() default -1;

String initialDelayString() default "";

}

Attribute Description
cron A cron-like expression, extending the usual UN*X definition to include triggers on the second as well as minute, hour, day of month, month and day of week. e.g. "0 * * * * MON-FRI" means once per minute on weekdays (at the top of the minute - the 0th second).
@return an expression that can be parsed to a cron schedule| 

|zone | A time zone for which the cron expression will be resolved. By default, this attribute is the empty String (i.e. the server's local time zone will be used).| |fixedDelay | Execute the annotated method with a fixed period in milliseconds between the end of the last invocation and the start of the next.

@return the delay in milliseconds

| |fixedDelayString | Execute the annotated method with a fixed period in milliseconds between the end of the last invocation and the start of the next.

@return the delay in milliseconds as a String value, e.g. a placeholder

| |fixedRate | Execute the annotated method with a fixed period in milliseconds between invocations.

@return the period in milliseconds

| |fixedRateString | Execute the annotated method with a fixed period in milliseconds between invocations.

@return the period in milliseconds as a String value, e.g. a placeholder

| |initialDelay | Number of milliseconds to delay before the first execution of a fixedRate() or fixedDelay() task.

@return the initial delay in milliseconds

| |initialDelayString | Number of milliseconds to delay before the first execution of a fixedRate() or fixedDelay() task.

@return the initial delay in milliseconds as a String value, e.g. a placeholder

|

2- Configure Maven & web.xml pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>org.o7planning</groupId> <artifactId>SpringMVCSchedule</artifactId>

war

<version>0.0.1-SNAPSHOT</version> <name>SpringMVCSchedule Maven Webapp</name> <url>http://maven.apache.org</url> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency>

        <!-- Servlet Library -->
    <!-- http://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>3.1.0</version>
        <scope>provided</scope>
    </dependency>

    <!-- Spring dependencies -->
    <!-- http://mvnrepository.com/artifact/org.springframework/spring-core -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>4.3.2.RELEASE</version>
    </dependency>

    <!-- http://mvnrepository.com/artifact/org.springframework/spring-web -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-web</artifactId>
        <version>4.3.2.RELEASE</version>
    </dependency>

    <!-- http://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>4.3.2.RELEASE</version>
    </dependency>
</dependencies>
<build>
  <finalName>SpringMVCSchedule</finalName>
  <plugins>
 
      <!-- Config: Maven Tomcat Plugin -->
      <!-- http://mvnrepository.com/artifact/org.apache.tomcat.maven/tomcat7-maven-plugin -->
      <plugin>
          <groupId>org.apache.tomcat.maven</groupId>
          <artifactId>tomcat7-maven-plugin</artifactId>
          <version>2.2</version>
          <!-- Config: contextPath and Port (Default: /SpringMVCSchedule : 8080) -->
          <!--
          <configuration>
              <path>/</path>
              <port>8899</port>
          </configuration>
          -->  
      </plugin>
  </plugins>
</build> </project>

web.xml

<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">

<display-name>Spring MVC Schedule</display-name>

</web-app>

3- Configure Spring MVC ApplicationContextConfig.java

import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.view.InternalResourceViewResolver;

@Configuration @ComponentScan("org.o7planning.springmvcschedule.*") public class ApplicationContextConfig {

@Bean(name = "viewResolver")
public InternalResourceViewResolver getViewResolver() {
    InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
    viewResolver.setPrefix("/WEB-INF/pages/");
    viewResolver.setSuffix(".jsp");
    return viewResolver;
}

}

SpringWebAppInitializer.java

import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.ServletRegistration;

import org.springframework.web.WebApplicationInitializer; import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; import org.springframework.web.servlet.DispatcherServlet;

public class SpringWebAppInitializer implements WebApplicationInitializer {

@Override
public void onStartup(ServletContext servletContext) throws ServletException {
    AnnotationConfigWebApplicationContext appContext = new AnnotationConfigWebApplicationContext();
    appContext.register(ApplicationContextConfig.class);

    ServletRegistration.Dynamic dispatcher = servletContext.addServlet("SpringDispatcher",
            new DispatcherServlet(appContext));
    dispatcher.setLoadOnStartup(1);
    dispatcher.addMapping("/");
}

}

WebMvcConfig.java

import java.nio.charset.Charset; import java.util.Arrays; import java.util.List;

import org.springframework.context.annotation.Configuration; import org.springframework.http.MediaType; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.http.converter.StringHttpMessageConverter; import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration @EnableWebMvc public class WebMvcConfig extends WebMvcConfigurerAdapter {

private static final Charset UTF8 = Charset.forName("UTF-8");

// Config UTF-8 Encoding. @Override public void configureMessageConverters(List<HttpMessageConverter<?>> converters) { StringHttpMessageConverter stringConverter = new StringHttpMessageConverter(); stringConverter.setSupportedMediaTypes(Arrays.asList(new MediaType("text", "plain", UTF8))); converters.add(stringConverter);

   // Add other converters ...

}

// Static Resource Config // equivalents for mvc:resources/ tags @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/css/").addResourceLocations("/css/").setCachePeriod(31556926); registry.addResourceHandler("/img/").addResourceLocations("/img/").setCachePeriod(31556926); registry.addResourceHandler("/js/**").addResourceLocations("/js/").setCachePeriod(31556926); }

// Equivalent for mvc:default-servlet-handler/ tag @Override public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) { configurer.enable(); }

}g;

Configuration allows you to use Schedule:

import org.springframework.context.annotation.Configuration; import org.springframework.scheduling.annotation.EnableScheduling;

@Configuration @EnableScheduling public class SchedulerConfig {

// Declaring the beans are related to the schedule here if necessary.

}

4- fixedDelay and fixedRate

fixedDelay so với fixedRate

Bạn chỉ có thể sử dụng fixedDelay hoặc fixedRate trong @Schedule adnotation nhưng bạn không thể sử dụng cả hai cùng một lúc.

     FixedDelay là thời gian còn lại khi công việc được hoàn thành. Sau thời gian còn lại, nó sẽ thực hiện nhiệm vụ tiếp theo.
     FixedRate là khoảng thời gian giữa thời gian bắt đầu để thực hiện nhiệm vụ trước và thời gian bắt đầu để thực hiện nhiệm vụ tiếp theo, nó không phụ thuộc vào việc công việc trước đó đã hoàn thành hay không.

All rights reserved

Viblo
Hãy đăng ký một tài khoản Viblo để nhận được nhiều bài viết thú vị hơn.
Đăng kí