zoukankan      html  css  js  c++  java
  • SpringBoot2.0集成Quartz

    原文链接:https://www.jianshu.com/p/dc814e8014b0

    https://blog.csdn.net/upxiaofeng/article/details/79415108

    尝试使用springboot整合quartz实现定时任务持久化到数据库,并配置quartz的集群功能

    首先介绍除了Quartz外实现定时任务的简单方式:
    • timer
    • ScheduledThreadPoolExecutor
    • 以及spring自带的@Scheduled
    一:使用Timer创建简单的定时任务
    public class TimerDemo {
        public static void main(String[] args) {
            Timer timer = new Timer();
            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    System.out.println("TimerTask1 run" + LocalDateTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss")));
                }
            },1000,5000);//延时1s,之后每隔5s运行一次
        }
    }   
    

    有两点问题需要注意:
    1.scheduleAtFixedRateschedule的区别:scheduleAtFixedRate会尽量减少漏掉调度的情况,如果前一次执行时间过长,导致一个或几个任务漏掉了,那么会补回来,而schedule过去的不会补,直接加上间隔时间执行下一次任务。

    参考下面两篇文章:
    https://www.cnblogs.com/dolphin0520/p/3938991.html
    https://www.cnblogs.com/snailmanlilin/p/6873802.html

    2.同一个Timer下添加多个TimerTask,如果其中一个没有捕获抛出的异常,则全部任务都会终止运行。但是多个Timer是互不影响

     
    会提示使用ScheduledThreadPoolExecutor代替Timer方式
    二:使用ScheduledThreadPoolExecutor创建定时任务
    public class SchedulerDemo {
        public static void main(String[] args) {
            ScheduledExecutorService executorService = new ScheduledThreadPoolExecutor(5);
            executorService.scheduleWithFixedDelay(new Runnable() {
                @Override
                public void run() {
                    String now = LocalDateTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss"));
                    System.out.println("ScheduledThreadPoolExecutor1 run:"+now);
                }
            },1,2,TimeUnit.SECONDS);
        }
    }
    

    scheduleWithFixedDelayschedule类似,而scheduleAtFixedRatescheduleAtFixedRate一样会尽量减少漏掉调度的情况

    三:在springboot环境下使用@Scheduled创建定时任务
    1. 启动类添加@EnableScheduling
    2. 定时任务方法上添加@Scheduled
    @Component
    public class springScheduledDemo {
        @Scheduled(cron = "1/5 * * * * ?")
        public void testScheduled(){
            System.out.println("springScheduled run:" + LocalDateTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss")));
        }
    }
    

    这里的cron表达式我们可以参考网上的配置:https://www.jianshu.com/p/e9ce1a7e1ed1
    但是spring的@Scheduled只支持6位,年份是不支持的,带年份的7位格式会报错:Cron expression must consist of 6 fields (found 7 in "1/5 * * * * ? 2018")

    使用Quartz定时任务框架:
    一:主动创建并简单的使用Quartz方式

    Quartz的一些概念:


     
    quartz相关概念

    参考文档:https://www.w3cschool.cn/quartz_doc/quartz_doc-1xbu2clr.html

    1. 添加jar包依赖
    <dependency>
        <groupId>org.quartz-scheduler</groupId>
        <artifactId>quartz</artifactId>
        <version>2.3.0</version>
    </dependency>
    <dependency>
        <groupId>org.quartz-scheduler</groupId>
        <artifactId>quartz-jobs</artifactId>
        <version>2.3.0</version>
    </dependency>
    
    1. 实现Job接口并且在execute方法中实现自己的业务逻辑
    public class HelloworldJob implements Job {
        @Override
        public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
            System.out.println("Hello world!:" + jobExecutionContext.getJobDetail().getKey());
        }
    }
    

    3.创建JobDetail实例并定义Trigger注册到scheduler,启动scheduler开启调度

    public class QuartzDemo {
        public static void main(String[] args) throws Exception {
            SchedulerFactory schedulerFactory = new StdSchedulerFactory();
            Scheduler scheduler = schedulerFactory.getScheduler();
            // 启动scheduler
            scheduler.start();
            // 创建HelloworldJob的JobDetail实例,并设置name/group
            JobDetail jobDetail = JobBuilder.newJob(HelloworldJob.class)
                    .withIdentity("myJob","myJobGroup1")
                    //JobDataMap可以给任务传递参数
                    .usingJobData("job_param","job_param1")
                    .build();
            // 创建Trigger触发器设置使用cronSchedule方式调度
            Trigger trigger = TriggerBuilder.newTrigger()
                    .withIdentity("myTrigger","myTriggerGroup1")
                    .usingJobData("job_trigger_param","job_trigger_param1")
                    .startNow()
                    //.withSchedule(SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(5).repeatForever())
                    .withSchedule(CronScheduleBuilder.cronSchedule("0/5 * * * * ? 2018"))
                    .build();
            // 注册JobDetail实例到scheduler以及使用对应的Trigger触发时机
            scheduler.scheduleJob(jobDetail,trigger);
        }
    }
    

    SimpleTriggerCronTrigger的区别:SimpleTrigger在具体的时间点执行一次或按指定时间间隔执行多次,CronTrigger按Cron表达式的方式去执行更常用。

    二:配置Quartz的持久化方式

    Quartz保存工作数据默认是使用内存的方式,上面的简单例子启动时可以在控制台日志中看到JobStoreRAMJobStore使用内存的模式,然后是not clustered表示不是集群中的节点

     
    默认使用RAMJobStore
    1. 持久化则需要配置JDBCJobStore方式,首先到官网下载Quartz压缩包,解压后在docsdbTables目录下看到很多对应不同数据库的SQL脚本,我这里选择mysql数据库且使用innodb引擎对应是tables_mysql_innodb.sql,打开可以看到需要添加11个QRTZ_开头的表
       
      tables_mysql_innodb.sql
    2. classpath路径下也就是项目resources根目录下添加quartz.properties配置文件
    org.quartz.scheduler.instanceName = MyScheduler
    #开启集群,多个Quartz实例使用同一组数据库表
    org.quartz.jobStore.isClustered = true
    #分布式节点ID自动生成
    org.quartz.scheduler.instanceId = AUTO
    #分布式节点有效性检查时间间隔,单位:毫秒
    org.quartz.jobStore.clusterCheckinInterval = 10000
    #配置线程池线程数量,默认10个
    org.quartz.threadPool.threadCount = 10
    org.quartz.jobStore.class = org.quartz.impl.jdbcjobstore.JobStoreTX
    org.quartz.jobStore.driverDelegateClass = org.quartz.impl.jdbcjobstore.StdJDBCDelegate
    #使用QRTZ_前缀
    org.quartz.jobStore.tablePrefix = QRTZ_
    #dataSource名称
    org.quartz.jobStore.dataSource = myDS
    #dataSource具体参数配置
    org.quartz.dataSource.myDS.driver = com.mysql.jdbc.Driver
    org.quartz.dataSource.myDS.URL = jdbc:mysql://localhost:3306/testquartz?serverTimezone=UTC&useSSL=false&useUnicode=true&characterEncoding=UTF-8
    org.quartz.dataSource.myDS.user = root
    org.quartz.dataSource.myDS.password = 7777777
    org.quartz.dataSource.myDS.maxConnections = 5
    
    1. 默认使用C3P0连接池,添加依赖
    <dependency>
        <groupId>c3p0</groupId>
        <artifactId>c3p0</artifactId>
        <version>0.9.1.2</version>
    </dependency>
    

    修改自定义连接池则需要实现org.quartz.utils.ConnectionProvider接口quartz.properties添加配置
    org.quartz.dataSource.myDS(数据源名).connectionProvider.class=XXX(自定义ConnectionProvider全限定名)

    1. 启动后可以发现控制台输出信息:JobStoreTX,以及数据库中也添加了相关记录
       
      Quartz配置持久化成功
    三:SpringBoot2.0集成Quartz
    1. 只需要引入starter
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-quartz</artifactId>
    </dependency>
    
    1. 继承QuartzJobBean并重写executeInternal方法,与之前的实现Job接口类似
    public class HiJob extends QuartzJobBean {
        @Autowired
        HelloworldService myService;
        @Override
        protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException {
            myService.printHelloWorld();
            System.out.println("    Hi! :" + jobExecutionContext.getJobDetail().getKey());
        }
    }
    

    这里HelloworldService打印一条helloworld模拟调用service的场景

    1. 添加配置类
    @Configuration
    public class QuartzConfig {
        @Bean
        public JobDetail myJobDetail(){
            JobDetail jobDetail = JobBuilder.newJob(HiJob.class)
                    .withIdentity("myJob1","myJobGroup1")
                    //JobDataMap可以给任务execute传递参数
                    .usingJobData("job_param","job_param1")
                    .storeDurably()
                    .build();
            return jobDetail;
        }
        @Bean
        public Trigger myTrigger(){
            Trigger trigger = TriggerBuilder.newTrigger()
                    .forJob(myJobDetail())
                    .withIdentity("myTrigger1","myTriggerGroup1")
                    .usingJobData("job_trigger_param","job_trigger_param1")
                    .startNow()
                    //.withSchedule(SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(5).repeatForever())
                    .withSchedule(CronScheduleBuilder.cronSchedule("0/5 * * * * ? 2018"))
                    .build();
            return trigger;
        }
    }
    
    1. application.yml配置文件添加Quartz相关配置
    spring:
      #配置数据源
      datasource:
        driver-class-name: com.mysql.jdbc.Driver
        url: jdbc:mysql://localhost:3306/testquartz?serverTimezone=UTC&useSSL=false&useUnicode=true&characterEncoding=UTF-8
        username: root
        password: password
      quartz:
        #持久化到数据库方式
        job-store-type: jdbc
        initialize-schema: embedded
        properties:
          org:
            quartz:
              scheduler:
                instanceName: MyScheduler
                instanceId: AUTO
              jobStore:
                class: org.quartz.impl.jdbcjobstore.JobStoreTX
                driverDelegateClass: org.quartz.impl.jdbcjobstore.StdJDBCDelegate
                tablePrefix: QRTZ_
                isClustered: true
                clusterCheckinInterval: 10000
                useProperties: false
              threadPool:
                class: org.quartz.simpl.SimpleThreadPool
                threadCount: 10
                threadPriority: 5
                threadsInheritContextClassLoaderOfInitializingThread: true
    

    参考springboot文档
    以及其他教程:http://blog.yuqiyu.com/spring-boot-chapter47.html

     
    截取自springboot文档配置示例

    启动后可以发现使用的是项目统一的数据源:(LocalDataSourceJobStore extends JobStoreCMT
     
    LocalDataSourceJobStore
    1. Quartz使用同一组数据库表作集群只需要配置相同的instanceName实例名称,以及设置org.quartz.jobStore.isClustered = true
      启动两个节点后关闭其中正在跑任务的节点,另一个节点会自动检测继续运行定时任务

       
      自动切换
    2. 多任务的问题,多个JobDetail使用同一个Trigger报错:Trigger does not reference given job!,这样的话估计只能创建多组triggerJobDetail配对?

    scheduler.scheduleJob(jobDetail,trigger);
    // 一个Job可以对应多个Trigger,但多个Job绑定一个Trigger报错
    scheduler.scheduleJob(jobDetail2,trigger);



    SpringBoot自带schedule

    沿用的springboot少xml配置的优良传统,本身支持表达式等多种定时任务
    注意在程序启动的时候加上@EnableScheduling

    @Scheduled(cron="0/5 * * * * ?")
        public void job(){
            System.out.println("每五秒执行一次");
        }

    为什么要使用Quartz

    多任务情况下,quartz更容易管理,可以实现动态配置
    执行时间表达式:
    这里写图片描述
    表达式示例:
    这里写图片描述

    集成Quartz

    如何搭建springboot就不再细说,官网和网上的教程很多。

    maven依赖

    <dependency>
                <groupId>org.quartz-scheduler</groupId>
                <artifactId>quartz</artifactId>
                <version>2.2.1</version>
            </dependency>

    测试Job类
    SchedulerQuartzJob1和SchedulerQuartzJob2代码差不多就不一一列出

    package com.yvan.quartz.job;
    
    import org.quartz.Job;
    import org.quartz.JobExecutionContext;
    import org.quartz.JobExecutionException;
    /**
     * 实现Job接口
     * @author yvan
     *
     */
    public class SchedulerQuartzJob1 implements Job{
        private void before(){
            System.out.println("任务开始执行");
        }
    
        @Override
        public void execute(JobExecutionContext arg0) throws JobExecutionException {
            before();
            System.out.println("开始:"+System.currentTimeMillis());
            // TODO 业务
            System.out.println("结束:"+System.currentTimeMillis());
            after();
        }
    
        private void after(){
            System.out.println("任务开始执行");
        }
    
    }

    任务调用处理
    将其拆分成两个部分

    • 实例化Job,将任务触发器加入任务调度中
        private void startJob1(Scheduler scheduler) throws SchedulerException {
            // 通过JobBuilder构建JobDetail实例,JobDetail规定只能是实现Job接口的实例
            // JobDetail 是具体Job实例
            JobDetail jobDetail = JobBuilder.newJob(SchedulerQuartzJob1.class).withIdentity("job1", "group1").build();
            // 基于表达式构建触发器
            CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule("0/5 * * * * ?");
            // CronTrigger表达式触发器 继承于Trigger
            // TriggerBuilder 用于构建触发器实例
            CronTrigger cronTrigger = TriggerBuilder.newTrigger().withIdentity("job1", "group1")
                    .withSchedule(cronScheduleBuilder).build();
            scheduler.scheduleJob(jobDetail, cronTrigger);
        }
    
        private void startJob2(Scheduler scheduler) throws SchedulerException {
            JobDetail jobDetail = JobBuilder.newJob(SchedulerQuartzJob2.class).withIdentity("job2", "group2").build();
            CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule("0 0/5 * * * ?");
            CronTrigger cronTrigger = TriggerBuilder.newTrigger().withIdentity("job2", "group2")
                    .withSchedule(cronScheduleBuilder).build();
            scheduler.scheduleJob(jobDetail, cronTrigger);
        }
    • 对外提供关于动态管理任务的方法
        /**
         * 开始执行所有任务
         * 
         * @throws SchedulerException
         */
        public void startJob() throws SchedulerException {
            startJob1(scheduler);
            startJob2(scheduler);
            scheduler.start();
        }
    
        /**
         * 获取Job信息
         * 
         * @param name
         * @param group
         * @return
         * @throws SchedulerException
         */
        public String getJobInfo(String name, String group) throws SchedulerException {
            TriggerKey triggerKey = new TriggerKey(name, group);
            CronTrigger cronTrigger = (CronTrigger) scheduler.getTrigger(triggerKey);
            return String.format("time:%s,state:%s", cronTrigger.getCronExpression(),
                    scheduler.getTriggerState(triggerKey).name());
        }
    
        /**
         * 修改某个任务的执行时间
         * 
         * @param name
         * @param group
         * @param time
         * @return
         * @throws SchedulerException
         */
        public boolean modifyJob(String name, String group, String time) throws SchedulerException {
            Date date = null;
            TriggerKey triggerKey = new TriggerKey(name, group);
            CronTrigger cronTrigger = (CronTrigger) scheduler.getTrigger(triggerKey);
            String oldTime = cronTrigger.getCronExpression();
            if (!oldTime.equalsIgnoreCase(time)) {
                CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(time);
                CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity(name, group)
                        .withSchedule(cronScheduleBuilder).build();
                date = scheduler.rescheduleJob(triggerKey, trigger);
            }
            return date != null;
        }
    
        /**
         * 暂停所有任务
         * 
         * @throws SchedulerException
         */
        public void pauseAllJob() throws SchedulerException {
            scheduler.pauseAll();
        }
    
        /**
         * 暂停某个任务
         * 
         * @param name
         * @param group
         * @throws SchedulerException
         */
        public void pauseJob(String name, String group) throws SchedulerException {
            JobKey jobKey = new JobKey(name, group);
            JobDetail jobDetail = scheduler.getJobDetail(jobKey);
            if (jobDetail == null)
                return;
            scheduler.pauseJob(jobKey);
        }
    
        /**
         * 恢复所有任务
         * 
         * @throws SchedulerException
         */
        public void resumeAllJob() throws SchedulerException {
            scheduler.resumeAll();
        }
    
        /**
         * 恢复某个任务
         * 
         * @param name
         * @param group
         * @throws SchedulerException
         */
        public void resumeJob(String name, String group) throws SchedulerException {
            JobKey jobKey = new JobKey(name, group);
            JobDetail jobDetail = scheduler.getJobDetail(jobKey);
            if (jobDetail == null)
                return;
            scheduler.resumeJob(jobKey);
        }
    
        /**
         * 删除某个任务
         * 
         * @param name
         * @param group
         * @throws SchedulerException
         */
        public void deleteJob(String name, String group) throws SchedulerException {
            JobKey jobKey = new JobKey(name, group);
            JobDetail jobDetail = scheduler.getJobDetail(jobKey);
            if (jobDetail == null)
                return;
            scheduler.deleteJob(jobKey);
        }
    • 完整代码
    package com.yvan.quartz;
    
    import java.util.Date;
    
    import org.quartz.CronScheduleBuilder;
    import org.quartz.CronTrigger;
    import org.quartz.JobBuilder;
    import org.quartz.JobDetail;
    import org.quartz.JobKey;
    import org.quartz.Scheduler;
    import org.quartz.SchedulerException;
    import org.quartz.TriggerBuilder;
    import org.quartz.TriggerKey;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.context.annotation.Configuration;
    
    import com.yvan.quartz.job.SchedulerQuartzJob1;
    import com.yvan.quartz.job.SchedulerQuartzJob2;
    /**
     * 任务调度处理
     * @author yvan
     *
     */
    @Configuration
    public class QuartzScheduler {
        // 任务调度
        @Autowired
        private Scheduler scheduler;
    
        /**
         * 开始执行所有任务
         * 
         * @throws SchedulerException
         */
        public void startJob() throws SchedulerException {
            startJob1(scheduler);
            startJob2(scheduler);
            scheduler.start();
        }
    
        /**
         * 获取Job信息
         * 
         * @param name
         * @param group
         * @return
         * @throws SchedulerException
         */
        public String getJobInfo(String name, String group) throws SchedulerException {
            TriggerKey triggerKey = new TriggerKey(name, group);
            CronTrigger cronTrigger = (CronTrigger) scheduler.getTrigger(triggerKey);
            return String.format("time:%s,state:%s", cronTrigger.getCronExpression(),
                    scheduler.getTriggerState(triggerKey).name());
        }
    
        /**
         * 修改某个任务的执行时间
         * 
         * @param name
         * @param group
         * @param time
         * @return
         * @throws SchedulerException
         */
        public boolean modifyJob(String name, String group, String time) throws SchedulerException {
            Date date = null;
            TriggerKey triggerKey = new TriggerKey(name, group);
            CronTrigger cronTrigger = (CronTrigger) scheduler.getTrigger(triggerKey);
            String oldTime = cronTrigger.getCronExpression();
            if (!oldTime.equalsIgnoreCase(time)) {
                CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(time);
                CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity(name, group)
                        .withSchedule(cronScheduleBuilder).build();
                date = scheduler.rescheduleJob(triggerKey, trigger);
            }
            return date != null;
        }
    
        /**
         * 暂停所有任务
         * 
         * @throws SchedulerException
         */
        public void pauseAllJob() throws SchedulerException {
            scheduler.pauseAll();
        }
    
        /**
         * 暂停某个任务
         * 
         * @param name
         * @param group
         * @throws SchedulerException
         */
        public void pauseJob(String name, String group) throws SchedulerException {
            JobKey jobKey = new JobKey(name, group);
            JobDetail jobDetail = scheduler.getJobDetail(jobKey);
            if (jobDetail == null)
                return;
            scheduler.pauseJob(jobKey);
        }
    
        /**
         * 恢复所有任务
         * 
         * @throws SchedulerException
         */
        public void resumeAllJob() throws SchedulerException {
            scheduler.resumeAll();
        }
    
        /**
         * 恢复某个任务
         * 
         * @param name
         * @param group
         * @throws SchedulerException
         */
        public void resumeJob(String name, String group) throws SchedulerException {
            JobKey jobKey = new JobKey(name, group);
            JobDetail jobDetail = scheduler.getJobDetail(jobKey);
            if (jobDetail == null)
                return;
            scheduler.resumeJob(jobKey);
        }
    
        /**
         * 删除某个任务
         * 
         * @param name
         * @param group
         * @throws SchedulerException
         */
        public void deleteJob(String name, String group) throws SchedulerException {
            JobKey jobKey = new JobKey(name, group);
            JobDetail jobDetail = scheduler.getJobDetail(jobKey);
            if (jobDetail == null)
                return;
            scheduler.deleteJob(jobKey);
        }
    
        private void startJob1(Scheduler scheduler) throws SchedulerException {
            // 通过JobBuilder构建JobDetail实例,JobDetail规定只能是实现Job接口的实例
            // JobDetail 是具体Job实例
            JobDetail jobDetail = JobBuilder.newJob(SchedulerQuartzJob1.class).withIdentity("job1", "group1").build();
            // 基于表达式构建触发器
            CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule("0/5 * * * * ?");
            // CronTrigger表达式触发器 继承于Trigger
            // TriggerBuilder 用于构建触发器实例
            CronTrigger cronTrigger = TriggerBuilder.newTrigger().withIdentity("job1", "group1")
                    .withSchedule(cronScheduleBuilder).build();
            scheduler.scheduleJob(jobDetail, cronTrigger);
        }
    
        private void startJob2(Scheduler scheduler) throws SchedulerException {
            JobDetail jobDetail = JobBuilder.newJob(SchedulerQuartzJob2.class).withIdentity("job2", "group2").build();
            CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule("0 0/5 * * * ?");
            CronTrigger cronTrigger = TriggerBuilder.newTrigger().withIdentity("job2", "group2")
                    .withSchedule(cronScheduleBuilder).build();
            scheduler.scheduleJob(jobDetail, cronTrigger);
        }
    }
    
    • Scheduler 注入
      这里采用监听spring容器加载完毕后事件,启动任务调用
      将Scheduler交给spring初始化管理
    package com.yvan.quartz;
    
    import org.quartz.Scheduler;
    import org.quartz.SchedulerException;
    import org.quartz.SchedulerFactory;
    import org.quartz.impl.StdSchedulerFactory;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.context.ApplicationListener;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.context.event.ContextRefreshedEvent;
    
    @Configuration
    public class ApplicationStartQuartzJobListener implements ApplicationListener<ContextRefreshedEvent>{
        @Autowired
        private QuartzScheduler quartzScheduler;
    
        /**
         * 初始启动quartz
         */
        @Override
        public void onApplicationEvent(ContextRefreshedEvent event) {
            try {
                quartzScheduler.startJob();
                System.out.println("任务已经启动...");
            } catch (SchedulerException e) {
                e.printStackTrace();
            }
        }
    
        /**
         * 初始注入scheduler
         * @return
         * @throws SchedulerException
         */
        @Bean
        public Scheduler scheduler() throws SchedulerException{
            SchedulerFactory schedulerFactoryBean = new StdSchedulerFactory();
            return schedulerFactoryBean.getScheduler(); 
        }
    
    }
    • 封装API
      这里封装的API主要是为了方便动态管理执行任务,当然依赖这些接口也可以做一个界面来更直观的操作管理任务,这个就不再赘述。
    package com.yvan.controller.quartzApi;
    
    import org.quartz.SchedulerException;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    import com.yvan.quartz.QuartzScheduler;
    
    /**
     * 这里并没有采用restful风格 只是简单封装了一下api
     * 
     * @author yvan
     *
     */
    @RestController
    @RequestMapping("/quartz")
    public class QuartzApiController {
        @Autowired
        private QuartzScheduler quartzScheduler;
    
        @RequestMapping("/start")
        public void startQuartzJob() {
            try {
                quartzScheduler.startJob();
            } catch (SchedulerException e) {
                e.printStackTrace();
            }
        }
    
        @RequestMapping("/info")
        public String getQuartzJob(String name, String group) {
            String info = null;
            try {
                info = quartzScheduler.getJobInfo(name, group);
            } catch (SchedulerException e) {
                e.printStackTrace();
            }
            return info;
        }
    
        @RequestMapping("/modify")
        public boolean modifyQuartzJob(String name, String group, String time) {
            boolean flag = true;
            try {
                flag = quartzScheduler.modifyJob(name, group, time);
            } catch (SchedulerException e) {
                e.printStackTrace();
            }
            return flag;
        }
    
        @RequestMapping(value = "/pause")
        public void pauseQuartzJob(String name, String group) {
            try {
                quartzScheduler.pauseJob(name, group);
            } catch (SchedulerException e) {
                e.printStackTrace();
            }
        }
    
        @RequestMapping(value = "/pauseAll")
        public void pauseAllQuartzJob() {
            try {
                quartzScheduler.pauseAllJob();
            } catch (SchedulerException e) {
                e.printStackTrace();
            }
        }
    
        @RequestMapping(value = "/delete")
        public void deleteJob(String name, String group) {
            try {
                quartzScheduler.deleteJob(name, group);
            } catch (SchedulerException e) {
                e.printStackTrace();
            }
        }
    
    }
    
    • 运行结果
     任务已经启动...
    18-03-02 14:39:46,879  INFO TomcatEmbeddedServletContainer:201 - Tomcat started on port(s): 8080 (http)
      18-03-02 14:39:46,883  INFO Start:57 - Started Start in 3.18 seconds (JVM running for 3.47)
      任务开始执行
    开始:1519972790003
    结束:1519972790003
    任务开始执行
    任务开始执行
    开始:1519972795000
    结束:1519972795000
    任务开始执行
     
  • 相关阅读:
    学习JNA,Jnative
    JNative用法注意事项
    使用JNA替代JNI调用本地方法
    傅盛读书笔记:下一个Moonshot是什么?
    华为内部狂转好文:有关大数据,看这一篇就够了
    ws2_32.dll的妙用与删除 (禁网)
    保护颈椎重点按这三大穴位(图)
    在java中调用python方法
    在Windows中实现Java调用DLL(转载)
    java程序员,英语那点事
  • 原文地址:https://www.cnblogs.com/fswhq/p/13785780.html
Copyright © 2011-2022 走看看