Open In App

Spring Cloud Task

Last Updated : 28 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In Spring Boot, Spring Cloud Task is a framework within the Spring Cloud ecosystem, and it can be used to design the simplify the development of the short-lived microservices often referred to as the tasks and these tasks typically perform the specific job or the operation and then terminate once the job is completed. It can provide the features for the task orchestration, execution, monitoring, and management of the distributed system.

Key Terminologies

  • Task: Task can refer to the short-lived microservices or the application that can be performs the specific job operation and then terminates.
  • Task Application: It is a Spring Boot application that can include the necessary dependencies and configurations to support the creation, execution, and management of the tasks using Spring Cloud Task.
  • Task Execution: It can be referred to as the process of running the task application to perform it is designated job. It can involve the task, executing the logic, and handling the errors.
  • Task Executor: It is responsible for launching and managing the execution of the tasks within a spring cloud task environment.
  • Task Parameters: These can be configurable inputs or arguments that can be passed to the task application during the execution and these parameters can influence the behavior of the task.
  • Task Monitoring: It can be used to track the status, progress, and metrics of the task execution and monitoring capabilities provided by the Spring Cloud Task.

Implementation of Spring Cloud Task

We can develop the spring application that can take the employee CSV file as input and that CSV file contains the names and salaries then Spring Cloud Task can process the file then generate the output CSV that can calculate the bonus of the employees.

Below is the step-by-step process to implement Spring Cloud Task.

Step 1: We can create the spring project using Spring STS IDE including the below mentioned dependencies into the project.

Dependencies

  • Spring Data for JPA
  • Spring Web
  • Lombok
  • Spring Dev Tools
  • Spring Cloud Task

Once complete the creation of the spring project then the spring project file structure look like the below image.

Project Structure


Step 2: Open the application.properties file and put the below code the database configuration.

spring.datasource.url= jdbc:mysql://localhost:3306/employee
spring.datasource.username= root
spring.datasource.password= password


Step 3: Create the csv file and it named as the employee.csv and it saved on the resource folder of the project.

name,salary
John Doe,50000
Jane Smith,60000
Michael Johnson,70000
Emily Davis,55000
Christopher Brown,62000
Jessica Wilson,58000
David Martinez,65000
Lisa Jones,53000
Matthew Taylor,68000
Amanda Anderson,51000


Step 4: Create the new package named as the model in that same package create the java class named as the Employee.

Go to src > com.gfg.springcloudtaskdemo > model > Employee and put the below code.

Employee.java:

Java
package com.gfg.springcloudtaskdemo.model;

import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data // Lombok annotation for generating getters, setters, and toString methods
@AllArgsConstructor // Lombok annotation for generating all-args constructor
@NoArgsConstructor // Lombok annotation for generating no-args constructor
@Entity // JPA annotation to indicate this class is an entity
public class Employee {
    @Id // JPA annotation to specify the primary key
    @GeneratedValue(strategy = GenerationType.IDENTITY) // JPA annotation to auto-generate the primary key
    private Long id; // Primary key
    private String name; // Name of the employee
    private double salary; // Salary of the employee

    // Constructor with name and salary parameters
    public Employee(String name, double salary) {
        this.name = name; // Initialize name
        this.salary = salary; // Initialize salary
    }

    // Constructors, getters, and setters are automatically generated by Lombok annotations
}


Step 5: Create the new package named as the service in that same package create the java class named as the BonusCalaculatorService.

Go to src > com.gfg.springcloudtaskdemo > service > BonusCalaculatorService and put the below code.

BonusCalaculatorService.java:

Java
package com.gfg.springcloudtaskdemo.service;

import org.springframework.stereotype.Service;

@Service
public class BonusCalculatorService {

    // Method to calculate bonus for a given salary
    public double calculateBonus(double salary) {
      
        return salary * 0.1;
    }
}


Step 6: Create the new package named as the task in that same package create the java class named as the BonusCalculationTask that can implements the CommandLineRunner.

Go to src > com.gfg.springcloudtaskdemo > task > BonusCalculationTask and put the below code.

BonusCalculationTask.java:

Java
package com.gfg.springcloudtaskdemo.task;

import com.gfg.springcloudtaskdemo.model.Employee;
import com.gfg.springcloudtaskdemo.service.BonusCalculatorService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

@Component
public class BonusCalculationTask implements CommandLineRunner {

    @Autowired
    private BonusCalculatorService bonusCalculatorService;

    @Override
    public void run(String... args) throws Exception {
        // Read input CSV file
        File inputFile = new File("C:/Users/Mahesh/Desktop/E-Commerce-Backend/SpringCloudTaskDemo/src/main/resources/employees.csv");
        List<Employee> employees = readEmployeesFromCSV(inputFile);

        // Process data (calculate bonus)
        calculateBonus(employees);

        // Write processed data to output CSV file
        File outputFile = new File("employees_with_bonus.csv");
        writeEmployeesToCSV(employees, outputFile);
    }

    private List<Employee> readEmployeesFromCSV(File file) throws IOException {
        List<Employee> employees = new ArrayList<>();
        try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
            String line;
            boolean headerSkipped = false; // Flag to track whether header row has been skipped
            while ((line = reader.readLine()) != null) {
                if (!headerSkipped) {
                    // Skip the header row
                    headerSkipped = true;
                    continue;
                }
                String[] parts = line.split(",");
                if (parts.length == 2) {
                    String name = parts[0];
                    double salary = Double.parseDouble(parts[1]);
                    employees.add(new Employee(name, salary));
                }
            }
        }
        return employees;
    }


    private void calculateBonus(List<Employee> employees) {
        for (Employee employee : employees) {
            double bonus = bonusCalculatorService.calculateBonus(employee.getSalary());
            employee.setSalary(employee.getSalary() + bonus);
        }
    }

    private void writeEmployeesToCSV(List<Employee> employees, File file) throws IOException {
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(file))) {
            for (Employee employee : employees) {
                writer.write(employee.getName() + "," + employee.getSalary());
                writer.newLine();
            }
        }
    }
}


Step 7: Open the main class and put the below code.

Java
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

// Entry point of the Spring Boot application
@SpringBootApplication
public class SpringCloudTaskDemoApplication {

    // Main method that starts the Spring Boot application
    public static void main(String[] args) {
        // Running the Spring Boot application
        SpringApplication.run(SpringCloudTaskDemoApplication.class, args);
    }

}


Step 8: Once completed the project runs the application as spring project its runs successfully then the runs the application at port 8080. Refer the below image for the better understanding.

Application Runs

Output:

Once runs the application, task out csv file can be generated to calculate the bonuses of the employee and its out-csv file will be located on the project root folder.

employees_with_bonuses.csv:

John Doe,55000.0
Jane Smith,66000.0
Michael Johnson,77000.0
Emily Davis,60500.0
Christopher Brown,68200.0
Jessica Wilson,63800.0
David Martinez,71500.0
Lisa Jones,58300.0
Matthew Taylor,74800.0
Amanda Anderson,56100.0

We can follow the above steps then we can successfully build the spring application of the spring cloud task. This project can be calculating the bonuses of the employees.


Next Article

Similar Reads