如何在工作完成后发送电子邮件?

How to send an e-mail after a job has finished?

我创建了一个捆绑多个批处理作业的应用程序。用户可以启动一个作业,然后将其放入队列中。作业完成后,我想向用户发送报告。

我知道有JobExecutionListener接口。我可以在 afterJob() 方法中实现电子邮件功能。下一步是将此侦听器注册到我的作业中。

有没有办法自动处理我的所有作业?我不想为每个新工作都配置它。

我创建了一个自定义 BeanPostProcessor 将侦听器添加到作业中:

@Component
public class MailListenerBeanPostProcessor implements BeanPostProcessor {

    @Autowired
    private MailListener listener;

    @Override
    public Object postProcessBeforeInitialization(final Object bean, final String beanName) throws BeansException {
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(final Object bean, final String beanName) throws BeansException {
        if (bean instanceof AbstractJob) {
            final AbstractJob job = (AbstractJob) bean;

            job.registerJobExecutionListener(listener);
        }

        return bean;
    }

}

你可以有这样的东西...

public class CustomJobExecutionListener implements JobExecutionListener {

    public void beforeJob(JobExecution arg0) {
      // send email here
    }

    public void afterJob(JobExecution arg0) {
        ExitStatus exitStatus = arg0.getExitStatus();
        String code = exitStatus.getExitCode();
        // send email here
    }

}

XML 配置:-

<bean id="customJobExecutionListener" class="com.myBatch.CustomJobExecutionListener"/>

       <batch:job id="job1" restartable="true">
        <batch:listeners>
            <batch:listener ref="customJobExecutionListener" />
        </batch:listeners>
                ...
                ...
        </batch:job>