Spring Cloud Task 集成Spring Cloud Task Batch(三)

2023-04-17 10:40:24 浏览数 (1)

创建TaskExecutor

现在我们需要创建一个TaskExecutor,它将用于启动Spring Batch作业。为此,我们将创建一个TaskLauncher实现,如下所示:

代码语言:javascript复制
import org.springframework.batch.core.Job;
import org.springframework.batch.core.JobExecution;
import org.springframework.batch.core.JobParameters;
import org.springframework.batch.core.JobParametersBuilder;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.task.listener.TaskExecutionListener;
import org.springframework.cloud.task.repository.TaskExecution;
import org.springframework.cloud.task.repository.TaskExplorer;
import org.springframework.cloud.task.repository.TaskRepository;
import org.springframework.stereotype.Component;

@Component
public class BatchTaskExecutor {

    @Autowired
    private JobLauncher jobLauncher;

    @Autowired
    private Job job;

    @Autowired
    private TaskRepository taskRepository;

    @Autowired
    private TaskExplorer taskExplorer;

    @Autowired
    private TaskExecutionListener taskExecutionListener;

    public void execute(TaskExecution taskExecution) throws Exception {

        JobParameters jobParameters = new JobParametersBuilder()
                .addLong("time", System.currentTimeMillis())
                .toJobParameters();

        JobExecution jobExecution = jobLauncher.run(job, jobParameters);

        taskExecution.setExitMessage(jobExecution.getExitStatus().getExitDescription());
        taskExecution.setEndTime(jobExecution.getEndTime());
        taskExecution.setExitCode(jobExecution.getExitStatus().getExitCode());
        taskExecution.setTaskName(jobExecution.getJobInstance().getJobName());
        taskExecution.setStartTime(jobExecution.getStartTime());
        taskExecution.setErrorMessage(jobExecution.getExitStatus().getExitDescription());
        taskRepository.update(taskExecution);

        taskExplorer.updateTaskExecution(taskExecution);
    }
}

这个类中,我们注入了jobLauncher,job,taskRepository,taskExplorer和taskExecutionListener。我们定义了一个execute方法,该方法将使用jobLauncher启动作业,然后将任务执行的结果存储在taskExecution对象中,并将其更新到taskRepository和taskExplorer中。

0 人点赞