# 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="https://1374779285-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MFW3x2aqEO8GF2kr3VU%2Fuploads%2FvcXpzGYTznhPG31qxyyW%2Fimage.png?alt=media&#x26;token=3368f67f-f845-41a5-b42f-0368feb83e74" 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.
