<%_ if (position === 'import') { _%>
import org.quartz.*;
import java.util.Date;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import <%= packageName %>.web.rest.errors.CommonException;
import <%= packageName %>.domain.enumeration.JobStatus;
import java.util.Objects;
<%_ } _%>
<%_ if (position === 'classExtend') { _%>
import org.quartz.*;
<%_ } _%>
<%_ if (position === 'extendsImport') { _%>
import org.quartz.*;
<%_ } _%>
<%_ if (position === 'classImplements') { _%>
<%_ } _%>
<%_ if (position === 'methodInterface') { _%>
<%_ } _%>
<%_ if (position === 'method') { _%>
    private static final String taskIdPrefix = "huayu_task_";
    <%_ if (ormTool === 'mybatis') { _%>

    /**
     * 保存&启动定时任务
     */
    @Transactional
    public boolean saveAndScheduleJob(TaskJobConfig taskJobConfig) {
        // DB设置修改
        boolean success = this.save(taskJobConfig);
        if (success) {
            if (JobStatus.NORMAL.equals(taskJobConfig.getJobStatus())) {
                // 定时器添加
                this.schedulerAdd(taskIdPrefix + taskJobConfig.getId(), taskJobConfig.getJobClassName().trim(), taskJobConfig.getCronExpression().trim(), taskJobConfig.getParameter());
            }
        }
        return success;
    }

    /**
     * 恢复定时任务
     */
    @Transactional
    public boolean resumeJob(Long id) {
        TaskJobConfig taskJobConfig = taskJobConfigRepository.selectById(id);
        schedulerDelete(taskIdPrefix + taskJobConfig.getId());
        schedulerAdd(taskIdPrefix + taskJobConfig.getId(), taskJobConfig.getJobClassName().trim(), taskJobConfig.getCronExpression().trim(), taskJobConfig.getParameter());
        taskJobConfig.setJobStatus(JobStatus.NORMAL);
        return this.updateById(taskJobConfig);
    }

    /**
     * 编辑&启停定时任务
     * @throws SchedulerException
     */
    @Transactional
    public boolean editAndScheduleJob(TaskJobConfig taskJob) throws SchedulerException {
        if (JobStatus.NORMAL.equals(taskJob.getJobStatus())) {
            schedulerDelete(taskIdPrefix + taskJob.getId());
            schedulerAdd(taskIdPrefix + taskJob.getId(), taskJob.getJobClassName().trim(), taskJob.getCronExpression().trim(), taskJob.getParameter());
        }else{
            scheduler.pauseJob(JobKey.jobKey(taskIdPrefix + taskJob.getId()));
        }
        return this.updateById(taskJob);
    }

    /**
     * 删除&停止删除定时任务
     */
    @Transactional
    public boolean deleteAndStopJob(TaskJobConfig job) {
        schedulerDelete(taskIdPrefix + job.getId());
        return this.removeById(job.getId());
    }

    public void execute(Long id) throws Exception {
        TaskJobConfig taskJobConfig = taskJobConfigRepository.selectById(id);
        if (Objects.isNull(taskJobConfig)) {
            throw new CommonException("notExist", "定时任务不存");
        }
        String jobName = taskJobConfig.getJobClassName().trim();
        Date startDate = new Date();
        DateTimeFormatter yyyyMMddHHmmss = DateTimeFormatter.ofPattern("yyyyMMddHHmmss").withZone(ZoneOffset.systemDefault());
        String ymd = yyyyMMddHHmmss.format(startDate.toInstant());
        String identity =  jobName + ymd;
        startDate.setTime(startDate.getTime() + 100L);
        SimpleTrigger trigger = (SimpleTrigger) TriggerBuilder.newTrigger()
            .withIdentity(identity, "immediate_group")
            .startAt(startDate)
            .build();
        JobDetail jobDetail = JobBuilder.newJob(getClass(jobName).getClass()).withIdentity(identity).usingJobData("parameter", taskJobConfig.getParameter()).build();
        scheduler.scheduleJob(jobDetail, trigger);
        scheduler.start();
    }

    @Transactional
    public void pause(Long id){
        TaskJobConfig quartzJob = taskJobConfigRepository.selectById(id);
        schedulerDelete(taskIdPrefix + quartzJob.getId());
        quartzJob.setJobStatus(JobStatus.PAUSED);
        this.updateById(quartzJob);
    }

    /**
     * 添加定时任务
     *
     * @param jobClassName 类名
     * @param cronExpression 定时表达式
     * @param parameter 参数
     */
    private void schedulerAdd(String id, String jobClassName, String cronExpression, String parameter) {
        try {
            // 启动调度器
            scheduler.start();

            // 构建job信息
            JobDetail jobDetail = JobBuilder.newJob(getClass(jobClassName).getClass()).withIdentity(id).usingJobData("parameter", parameter).build();

            // 表达式调度构建器(即任务执行的时间)
            CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(cronExpression);

            // 按新的cronExpression表达式构建一个新的trigger
            CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity(id).withSchedule(scheduleBuilder).build();

            scheduler.scheduleJob(jobDetail, trigger);
        } catch (SchedulerException e) {
            throw new CommonException("createJobFailure","创建定时任务失败");
        } catch (RuntimeException e) {
            throw new CommonException("runJobFailure","创建定时任务失败");
        }catch (Exception e) {
            throw new CommonException("classNotFound","后台找不到该类名：" + jobClassName);
        }
    }

    /**
     * 删除定时任务
     *
     * @param id 任务ID
     */
    private void schedulerDelete(String id) {
        try {
            scheduler.pauseTrigger(TriggerKey.triggerKey(id));
            scheduler.unscheduleJob(TriggerKey.triggerKey(id));
            scheduler.deleteJob(JobKey.jobKey(id));
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
            throw new CommonException("deleteJobFailure","删除定时任务失败");
        }
    }

    private static Job getClass(String classname) throws Exception {
        Class<?> class1 = Class.forName(classname);
        return (Job) class1.newInstance();
    }
    <%_ } _%>
<%_ } _%>
