# Quartz vs Spring Batch

## Introduction

* Spring Batch and Quartz are both popular frameworks used for scheduling and executing tasks in Java applications

## Spring Batch

### Introduction

* a lightweight framework specifically designed for batch processing. It provides a set of features and abstractions to handle complex batch workflows, such as reading data from various sources, processing it, and writing the results.
* well-suited for scenarios like data extraction, transformation, and loading (ETL), data synchronization, and large-scale data processing.

<figure><img src="/files/SAYmCBDGzqGebmNTLfvK" alt=""><figcaption></figcaption></figure>

* Each job launcher launch for a job
* Each job can include multiple step, and each step must include read, processor , writer
* The reader and writer resource can be from database, file, etc
* The processor is for transformation and business logic
* The tables is needed to be created for the job and map to job repository

### Example

```java
@Configuration
public class BatchConfiguration {

    @Autowired
    private JobLauncher jobLauncher;

    @Autowired
    private JobRepository jobRepository;

    @Autowired
    private PlatformTransactionManager transactionManager;
    
    @Bean
    public FlatFileItemReader<Person> reader() {
        return new FlatFileItemReaderBuilder<Person>()
                .name("personItemReader")
                .resource(new ClassPathResource("sample-data.csv"))
                .delimited()
                .names(new String[]{"firstName", "lastName"})
                .fieldSetMapper(new BeanWrapperFieldSetMapper<Person>() {{
                    setTargetType(Person.class);
                }})
                .build();
    }

    @Bean
    public PersonItemProcessor processor() {
        return new PersonItemProcessor();
    }

    @Bean
    public ItemWriter<Person> writer() {
        return new FlatFileItemWriterBuilder<Person>()
                .name("itemWriter")
                .resource(new FileSystemResource("src/resources/output-data.csv"))
                .lineAggregator(new PassThroughLineAggregator<>())
                .build();
    }


    @Bean
    public Step step1() {
        return new StepBuilder("step1", jobRepository)
                .<Person, Person>chunk(10, transactionManager)
                .reader(reader())
                .processor(processor())
                .writer(writer())
                .build();
    }

    @Bean
    public Job importUserJob() {
        return new JobBuilder("importUserJob", jobRepository)
                .incrementer(new RunIdIncrementer())
                .flow(step1())
                .end()
                .build();
    }

    @Scheduled(fixedRate = 10000)
    public void launchJob() throws Exception {
        JobExecution jobExecution = jobLauncher.run(importUserJob(), new JobParameters());
        System.out.println("Job Status : " + jobExecution.getStatus());
        System.out.println("Job completed");
    }
}
```

```java
public class PersonItemProcessor implements ItemProcessor<Person, Person> {

    private static final Logger log = LoggerFactory.getLogger(PersonItemProcessor.class);

    @Override
    public Person process(final Person person) throws Exception {
        final String firstName = person.getFirstName().toUpperCase();
        final String lastName = person.getLastName().toUpperCase();

        final Person transformedPerson = new Person(firstName, lastName);

        log.info("Converting (" + person + ") into (" + transformedPerson + ")");

        return transformedPerson;
    }
}
```

```java
package com.example.demo;

public class Person {

    private String lastName;
    private String firstName;

    public Person() {
    }

    public Person(String firstName, String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getFirstName() {
        return firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    @Override
    public String toString() {
        return "firstName: " + firstName + ", lastName: " + lastName;
    }
}
```

## Quartz

* It is a powerful open-source job scheduling library that can be used in any Java application
* It provides advanced scheduling capabilities, including cron-like expressions, interval-based triggers, and calendar-based scheduling
* It is suitable for scheduling various types of tasks, such as sending emails, generating reports, performing system maintenance, or running background jobs at specific intervals.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://petercheng7788.gitbook.io/developer-note/backend/spring/quartz-vs-spring-batch.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
