Search code examples
spring-bootkotlinspring-batchschedule

Can I pass an entity to a batch and use it in a job?


I have batch job code as below

import kr.test.testApp.core.domain.user.UserRepository
import mu.KotlinLogging
import org.springframework.batch.core.Job
import org.springframework.batch.core.Step
import org.springframework.batch.core.configuration.annotation.StepScope
import org.springframework.batch.core.job.builder.JobBuilder
import org.springframework.batch.core.repository.JobRepository
import org.springframework.batch.core.step.builder.StepBuilder
import org.springframework.batch.core.step.tasklet.Tasklet
import org.springframework.batch.repeat.RepeatStatus
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.transaction.PlatformTransactionManager

private val log = KotlinLogging.logger {  }

@Configuration
class BatchConfig(
    val jobRepository: JobRepository,
    val transactionManager: PlatformTransactionManager,
    val userRepository: UserRepository,
){
    @Bean
    fun myJob(): Job {
        return JobBuilder("taskletJob", jobRepository)
            .start(myStep())
            .build()
    }

    @Bean
    fun myStep(): Step {
        return StepBuilder("taskletStep", jobRepository)
            .allowStartIfComplete(true)
            .tasklet(myTask(), transactionManager)
            .build()
    }

    @Bean
    @StepScope
    fun myTask(): Tasklet {
        return Tasklet { _, _ ->
            log.info { " test job " } // i want output userid
            RepeatStatus.FINISHED
        }
    }
}

Use a schedule to run a batch every time at a set time, How to load a specific user from the database when running the batch and send this data to the job and use this user in the job?

@Scheduled(cron = "30 * * * * *")
fun batchGo(){
    val user = userRepository.findByIdOrNull(1) ?: throw Exception("user not found")

    val jobParameters = JobParametersBuilder()
        .toJobParameters()

    val jobExecution: JobExecution = jobLauncher.run(batchConfig.myJob(),jobParameters)
    if (jobExecution.status == BatchStatus.COMPLETED) {
        println("batch success")
    } else {
        println("no")
    }
}

As a result, after pulling the user out of the database, we pass it to the batch run, I want to print the ID of the user passed to myTask() log part, can you give me some advice?


Solution

  • You can pass the user ID as a job parameter:

    String userId = ...
    val jobParameters = JobParametersBuilder()
            .addString("userId", userId)
            .toJobParameters()
    

    and get it in the tasklet through the StepContribution#getStepExecution#getJobParameters or ChunkContext#getStepContext#getJobParameters.

    @Bean
    @StepScope
    fun myTask(): Tasklet {
       return Tasklet { (contribution, chunkContext) ->
                String userId = contribution.getStepExecution().getJobParameters().getString("userId");
                log.info { " test job " } // i want output userid
                RepeatStatus.FINISHED
       }
    }