Master Spring Cloud Task: Build Short-Lived Microservices with Java

This guide walks you through setting up Spring Cloud Task on Spring Boot 2.7 with Spring Cloud 2021, covering environment requirements, Maven dependencies, configuration files, task annotations, ApplicationRunner implementation, database schema, task listeners, and advanced task configuration options.

Spring Full-Stack Practical Cases
Spring Full-Stack Practical Cases
Spring Full-Stack Practical Cases
Master Spring Cloud Task: Build Short-Lived Microservices with Java

1. Introduction

Spring Cloud Task enables developers to create and run short‑lived microservices using Spring Cloud, suitable for prototype development, batch jobs, or real‑time data processing. Adding @EnableTask to a Spring Boot application activates the task framework.

Environment Requirements

Java 8 or higher.

A relational database for persisting task execution results. Supported databases include DB2, H2, HSQLDB, MySQL, Oracle, PostgreSQL, and SQL Server.

2. Practical Example

Dependency Management

<dependency>
  <groupId>org.springframework.cloud</groupId>
  <artifactId>spring-cloud-starter-task</artifactId>
</dependency>
<dependency>
  <groupId>com.mysql</groupId>
  <artifactId>mysql-connector-j</artifactId>
  <scope>runtime</scope>
</dependency>
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>

Configuration File (application.yml)

spring:
  datasource:
    driverClassName: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/xxxx?serverTimezone=GMT+8&useSSL=false
    username: root
    password: xxxxxx
    type: com.zaxxer.hikari.HikariDataSource

Enable Task

@SpringBootApplication
@EnableTask
public class SpringcloudTaskApplication {
}

ApplicationRunner Implementation

@Component
public class PackApplicationRunner implements ApplicationRunner {
    @Override
    public void run(ApplicationArguments args) throws Exception {
        System.out.println("PackApplicationRunner...");
    }
}

When the ApplicationRunner finishes, the program exits automatically. If the runner performs a long‑running job, the JVM waits until the job completes before shutting down.

After execution, Spring Cloud Task creates several tables (e.g., task_execution, task_execution_params) to store execution metadata such as start/end times, task name, exit code, and command‑line arguments.

The task_execution table records each task’s start and end timestamps, while task_execution_params stores any command‑line arguments passed at launch.

3. Task Configuration

Table Prefix

spring:
  cloud:
    task:
      table-prefix: TASK_

If a custom prefix is used, you must create the corresponding DDL in your database.

Enable/Disable Table Initialization

Set spring.cloud.task.initialize-enabled=false to prevent automatic table creation on startup.

External Execution ID

spring:
  cloud:
    task:
      external-execution-id: 888

This value is stored in the task_execution table and can be used to correlate tasks with external systems.

Parent Execution ID

spring:
  cloud:
    task:
      external-execution-id: 888
      parent-execution-id: 999

Allows nesting of tasks by recording a parent task identifier.

Custom TaskConfigurer

@Component
public class PackTaskConfigurer implements TaskConfigurer {
    @Override
    public TaskRepository getTaskRepository() { return null; }
    @Override
    public PlatformTransactionManager getTransactionManager() { return null; }
    @Override
    public TaskExplorer getTaskExplorer() { return null; }
    @Override
    public DataSource getTaskDataSource() { return null; }
}

Task Execution Listener

@Component
public class PackTaskExecutionListener implements TaskExecutionListener {
    @Override
    public void onTaskStartup(TaskExecution taskExecution) {
        System.out.println("PackTaskExecutionListener onTaskStartup ...");
    }
    @Override
    public void onTaskEnd(TaskExecution taskExecution) {
        System.out.println("PackTaskExecutionListener onTaskEnd ...");
    }
    @Override
    public void onTaskFailed(TaskExecution taskExecution, Throwable throwable) {
        System.out.println("PackTaskExecutionListener onTaskFailed ...");
    }
}

Alternatively, use annotation‑based listeners:

@Component
public class PackBeforeAfterFailedTask {
    @BeforeTask
    public void beforeTask(TaskExecution taskExecution) { System.out.println("before..."); }
    @AfterTask
    public void afterTask(TaskExecution taskExecution) { System.out.println("after..."); }
    @FailedTask
    public void failedTask(TaskExecution taskExecution) { System.out.println("failed..."); }
}

Console output example:

before...
PackTaskExecutionListener onTaskStartup ...
2023-12-20 22:27:00.329  INFO 8280 --- [           main] com.pack.SpringcloudTaskApplication      : Started SpringcloudTaskApplication in 1.023 seconds (JVM running for 1.211)
PackApplicationRunner...
PackTaskExecutionListener onTaskEnd ...
after...

Limit Concurrent Instances

Enable single‑instance mode to ensure only one task with a given name runs at a time:

spring:
  cloud:
    task:
      single-instance-enabled: true

Additional dependencies required:

<dependency>
  <groupId>org.springframework.integration</groupId>
  <artifactId>spring-integration-core</artifactId>
</dependency>
<dependency>
  <groupId>org.springframework.integration</groupId>
  <artifactId>spring-integration-jdbc</artifactId>
</dependency>

If a second instance of the same task starts while the first is still running, Spring Cloud Task throws an error indicating the task is already in execution.

Conclusion

Spring Cloud Task provides a lightweight framework for developing and running short‑lived microservices on the JVM, offering built‑in support for task lifecycle management, database persistence, custom listeners, and execution constraints, making it ideal for prototypes, batch jobs, and real‑time processing scenarios.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Javamicroservicestask schedulingSpring BootSpring Cloud Task
Spring Full-Stack Practical Cases
Written by

Spring Full-Stack Practical Cases

Full-stack Java development with Vue 2/3 front-end suite; hands-on examples and source code analysis for Spring, Spring Boot 2/3, and Spring Cloud.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.