Java.util.concurrent.ScheduledExecutorServiceとSpringを組み合わせたquartzのcron構成


JAvaのいくつかのタイミングタスクの比較:いくつかのタスクスケジューリングjava実装スキーム
 
私は最近springのタイミングタスクソースコードを見て、ScheduledExecutorを使ってquartzのcron式の構成を実現できることを発見しました.ページを変更してcron式を構成することで、より柔軟な構成を実現できるようになりました.
 
追加された機能は次のとおりです.
1、タスクのオンとオフ
2、cron式を修正し、自動的にタスクを再発行する
3、注釈に基づく配置
4、タスクをデータベースに永続化する
 
Springコンテナの起動時に注記されたすべてのメソッドをスキャンし、起動するタスク(コード48行)を発行します.
@Component
public class TaskConfig implements BeanPostProcessor, ApplicationContextAware, ApplicationListener<ContextRefreshedEvent> {

    private ApplicationContext applicationContext;

    private Set<JobDetail> jobDetails = new HashSet<JobDetail>();

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

    @Override
    public Object postProcessAfterInitialization(final Object bean, String beanName) throws BeansException {
        if (!bean.getClass().getCanonicalName().startsWith("com.xxx.task")) {
            return bean;
        }
        final Class<?> targetClass = AopUtils.getTargetClass(bean);
        ReflectionUtils.doWithMethods(targetClass, new ReflectionUtils.MethodCallback() {
            public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException {
                Job annotation = AnnotationUtils.getAnnotation(method, Job.class);
                if (annotation != null) {
                    JobDetail job = new JobDetail();
                    job.setCronExp(annotation.cron());
                    job.setJobClass(bean.getClass());
                    job.setJobName(annotation.name());
                    job.setValid(true);
                    job.setMethodName(method.getName());
                    jobDetails.add(job);
                }
            }
        });
        return bean;
    }

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        if (event.getApplicationContext() != this.applicationContext) {
            return;
        }

        for (JobDetail job : jobDetails) {
            JobService jobService = applicationContext.getBean(JobService.class);
            JobDetail jobDetail = jobService.findJobByName(job.getJobName());
            if (jobDetail == null) {
                jobDetail = job;
            }
            jobService.schedule(jobDetail);
        }
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}

 
またjobServiceに来ます:
@Service
public class JobService {
    private TaskScheduler taskScheduler = new ConcurrentTaskScheduler(Executors.newScheduledThreadPool(1));
    private final Map<String, ScheduledFuture<?>> scheduledFutures = new HashMap<String, ScheduledFuture<?>>();
    /**
     *   jobName task     , 
     */
    private Map<String, Runnable> runnableMap = new ConcurrentHashMap<String, Runnable>();
    private TriggerContext triggerContext = new SimpleTriggerContext();
    /**
     *   jobDetail        
     *                      
     * @param job
     */
    @Transactional
    public void schedule(final JobDetail job) {
        CronTrigger trigger = new CronTrigger(job.getCronExp());
        final CronSequenceGenerator sequenceGenerator = new CronSequenceGenerator(job.getCronExp(), TimeZone.getDefault());

        job.setNextExecTime(sequenceGenerator.next(new Date()));
        commonDao.saveOrUpdate(job);

        ErrorHandler errorHandler = new JobErrorHandler(job);
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                //                    
                JobDetail currentJob = findJobByName(job.getJobName());
                if (currentJob != null && currentJob.isValid()) {
                    Object o = SpringContextUtil.getBean(currentJob.getJobClass());
                    ReflectionUtils.invokeMethod(ReflectionUtils.findMethod(currentJob.getJobClass(),
                            currentJob.getMethodName()), o);
                    Date d = new Date();
                    currentJob.setLastExecTime(d);
                    currentJob.setNextExecTime(sequenceGenerator.next(new Date()));
                    commonDao.saveOrUpdate(currentJob);
                } else {
                    cancel(job.getJobName());
                }
            }
        };
        Runnable delegatingErrorHandlingRunnable = TaskUtils.decorateTaskWithErrorHandler(runnable, errorHandler, false);
        this.scheduledFutures.put(job.getJobName(), taskScheduler.schedule(delegatingErrorHandlingRunnable, trigger));
    }

    /**
     *     
     * @param jobName
     */
    @Transactional
    public void stopJob(String jobName) {
        String update = "update cms_sys_jobdetails set VALID='N' where JOB_NAME='" + jobName + "'";
        commonDao.getCurrentSession().createSQLQuery(update).executeUpdate();
        this.cancel(jobName);
    }

    /**
     *     
     * @param jobName
     */
    @Transactional
    public void startJob(String jobName) {
        JobDetail job = this.findJobByName(jobName);
        job.setValid(true);
        this.schedule(job);
    }

    /**
     *   cron   
     * @param jobName
     * @param cron
     */
    @Transactional
    public void resetCron(String jobName, String cron) {

        new CronSequenceGenerator(cron, TimeZone.getDefault());

        JobDetail job = this.findJobByName(jobName);
        job.setCronExp(cron);
        commonDao.saveOrUpdate(job);
        if (job.isValid()) {
            this.cancel(jobName);
            this.schedule(job);
        }
    }

    /**
     *         
     * @param jobName
     */
    private void cancel(String jobName) {
        ScheduledFuture r = scheduledFutures.get(jobName);
        if (r != null) {
            r.cancel(true); //  true          ,     ,          
        }
    }

    /**
     *         ErrorHandler
     */
    private class JobErrorHandler implements ErrorHandler {
        private JobDetail job;

        public JobErrorHandler(JobDetail job) {
            this.job = job;
        }

        private final Log logger = LogFactory.getLog(JobErrorHandler.class);

        @Override
        public void handleError(Throwable t) {
            logger.error("Unexpected error occurred in scheduled task===>" + job.getJobName(), t);
        }
    }

}

 
 
JobDetaiは、データベースに永続化する必要があるエンティティです.
@Entity
@Table(name = "CMS_SYS_JOBDETAILS")
public class JobDetail implements Serializable {
    private static final long serialVersionUID = 6899388713399265016L;

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE)
    private Long id;

    @Column(name="JOB_NAME", length = 255)
    private String jobName;

    @Column(name="CRON_EXP", length = 255)
    private String cronExp;

    @Column(name = "LAST_EXEC_TIME")
    @Temporal(TemporalType.TIMESTAMP)
    private Date lastExecTime;

    @Column(name = "NEXT_EXEC_TIME")
    @Temporal(TemporalType.TIMESTAMP)
    private Date nextExecTime;

    @Type(type = "yes_no")
    @Column(name = "VALID")
    private boolean valid;

    @Column(name = "JOB_CLASS")
    private Class jobClass;

    @Column(name = "METHOD_NAME")
    private String methodName;

    public String getMethodName() {
        return methodName;
    }

    public void setMethodName(String methodName) {
        this.methodName = methodName;
    }

    public Class getJobClass() {
        return jobClass;
    }

    public void setJobClass(Class jobClass) {
        this.jobClass = jobClass;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getJobName() {
        return jobName;
    }

    public void setJobName(String jobName) {
        this.jobName = jobName;
    }

    public String getCronExp() {
        return cronExp;
    }

    public void setCronExp(String cronExp) {
        this.cronExp = cronExp;
    }

    public Date getLastExecTime() {
        return lastExecTime;
    }

    public void setLastExecTime(Date lastExecTime) {
        this.lastExecTime = lastExecTime;
    }

    public Date getNextExecTime() {
        return nextExecTime;
    }

    public boolean isValid() {
        return valid;
    }

    public void setValid(boolean valid) {
        this.valid = valid;
    }

    public void setNextExecTime(Date nextExecTime) {
        this.nextExecTime = nextExecTime;
    }

}

 
 
カスタム注釈Jobは、すべてのタイミングタスクを必要とする方法に追加できます.
/**
 *                 ,name cron    ,            cron
 *               spring      {@link TaskConfig}         
 *           ,            。            API     
 * {@link com.xxx.service.JobService}   。
 *
 * @see com.xxx.service.JobService
 * @see TaskConfig
 * @author: bigtian
 * Date: 12-6-20
 * Time:   7:26
 */
@Target({ ElementType.TYPE, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
public @interface Job {
    String name();

    String cron();

}