Bootstrap

Quartz的增删查改

概述

在项目中使用到了Quartz,大概了解了一下其中的使用方式

demo

大致看了一下项目案例,Quartz从使用来说是用来定时执行某个bean的,如下是它的增删改操作,大体上来说Quartz就是通过JobDetail 和TriggerKey来完成定时任务的调度的,刚开始上手Quartz的读者,可以考虑文章末尾的连接

@Autowired
    private Scheduler scheduler;

    @Autowired
    private TJobDao tJobDao;

    private static final String JOB_DATA_KEY = "JOB_DATA_KEY";

    @Override
    public IPage pageData(Page<TJob> page, TJob job) {

        return tJobDao.selectPage(page, Wrappers.lambdaQuery(job));
    }


    @Override
    public void updateJob(TJob job) {

        tJobDao.updateById(job);

    }

    @Override
    public void saveJob(TJob tJob) throws Exception {

        /*
            new Job要求提供一个参数 Class<? extends Job> jobClass
            这个参数 是要求实现Job接口
            withIdentity 方法要求提供一个job名和组名
         */

        QueryWrapper<TJob> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(TJob::getJobName,tJob.getJobName());

        TJob job = tJobDao.selectOne(queryWrapper);

        JobKey jobKey = JobKey.jobKey(tJob.getJobName());

        if (scheduler.checkExists(jobKey)||job!=null){
            throw new Exception("jobName已存在");
        }

            tJobDao.insert(tJob);

            JobDetail jobDetail = JobBuilder.newJob(QuartzJob.class).withIdentity(jobKey).build();

            TriggerBuilder<Trigger> triggerBuilder = TriggerBuilder.newTrigger();
            triggerBuilder.withIdentity(tJob.getJobName(),"test_trigger");

            triggerBuilder.startNow();

            triggerBuilder.withSchedule(CronScheduleBuilder.cronSchedule(tJob.getCron()));

            CronTrigger trigger = (CronTrigger) triggerBuilder.build();

            scheduler.scheduleJob(jobDetail,trigger);

            scheduler.start();
            
    }

    @Override
    public void deleteJob(Integer id) throws SchedulerException {

        TJob tJob = tJobDao.selectById(id);

        if (tJob==null){
            return;
        }

        JobKey jobKey = JobKey.jobKey(tJob.getJobName());

        scheduler.pauseJob(jobKey);
        scheduler.unscheduleJob(new TriggerKey(tJob.getJobName()));
        scheduler.deleteJob(jobKey);

        /*
            删除了任务之后,更新任务状态
         */
        tJob.setStatus(false);
        tJobDao.updateById(tJob);

    }

文章连接

;