zoukankan      html  css  js  c++  java
  • spring task 和quartz任务 corn表达式

    SpringBoot整合定时任务task非常的简单,共分为以下三步:

    1. 在启动类加上@EnableScheduling注解

    2. 在controller的类上加上@Component注解

    3. 在controller的方法上加上@Scheduled注解即可

    之后启动程序,就会自动开始执行任务了

    SpringBoot整合定时任务task

    package com.example;
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.boot.builder.SpringApplicationBuilder;
    import org.springframework.boot.web.support.SpringBootServletInitializer;
    import org.springframework.scheduling.annotation.EnableScheduling;
    
    
    @SpringBootApplication
    //开启定时任务
    @EnableScheduling
    public class DemoApplication extends SpringBootServletInitializer {
        public static void main(String[] args) {
            SpringApplication.run(DemoApplication.class, args);
        }
    }
    @Component
    public class cronjobscontroller {
    
        private static final SimpleDateFormat dataFormat = new SimpleDateFormat("HH:mm:ss");
    
        //每隔三秒执行一次任务
        @Scheduled(fixedRate = 3000)
        public void cronJobs(){
            System.out.println("时间为:"+dataFormat.format(new Date()));
        }
    
    }

    在线cron表达式生成器地址:http://cron.qqe2.com/

    关于Quartz

    Quartz是OpenSymphony开源组织在Job scheduling领域又一个开源项目,它可以与J2EE与J2SE应用程序相结合也可以单独使用。在java企业级应用中,Quartz是使用最广泛的定时调度框架。

    在Quartz中的主要概念:

    • Scheduler:调度任务的主要API
    • ScheduleBuilder:用于构建Scheduler,例如其简单实现类SimpleScheduleBuilder
    • Job:调度任务执行的接口,也即定时任务执行的方法
    • JobDetail:定时任务作业的实例
    • JobBuilder:关联具体的Job,用于构建JobDetail
    • Trigger:定义调度执行计划的组件,即定时执行
    • TriggerBuilder:构建Trigger

    在SpringBoot中,我们需要引入quartz的依赖。

     <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    
    <!--quartz定时调度依赖-->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-quartz</artifactId>
    </dependency>

    首先定义定时具体执行逻辑Job,创建类QuartzJob1,这里集继承QuartzJobBean实现executeInternal即可,该方法即定时执行任务逻辑,这里简单打印了下当前时间。

    public class QuartzJob1 extends QuartzJobBean {
    
        @Override
        protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException {
            SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            System.out.println("QuartzJob1----" + sdf.format(new Date()));
        }
    
    }

    然后创建QuartzConfig,接着定义JobDetail,JobDetail由JobBuilder构建,同时关联了任务QuartzJob1。

    最后我们需要定义定时调度Trigger,简单实现类SimpleScheduleBuilder用于构建Scheduler,TriggerBuilder则用于构建Trigger,

    @Configuration
    public class QuartzConfig {
    
        @Bean
        public JobDetail jobDetail1(){
            return JobBuilder.newJob(QuartzJob1.class).storeDurably().build();
        }
    
        @Bean
        public Trigger trigger1(){
            SimpleScheduleBuilder scheduleBuilder = SimpleScheduleBuilder.simpleSchedule()
                    .withIntervalInSeconds(1) //每一秒执行一次
                    .repeatForever(); //永久重复,一直执行下去
            return TriggerBuilder.newTrigger()
                    .forJob(jobDetail1())
                    .withSchedule(scheduleBuilder)
                    .build();
        }
        
    }

    同时Quartz是支持数据持久化的,可以将定时调度信息持久化到数据库。

    选择持久化到数据库,我们需要创建对应的表,建表语句可以在Quartz官网进行下载,解压后在docsdbTables目录下寻找对应数据库的SQL脚本。

    为了方便,我也将该文件放在了项目源码resources里。

    操作数据库,我们引入相关的依赖。若有ORM框架,例如mybatis,hibernate或者jpa,则无需再引入jdbc依赖。

    <!--mysql连接-->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <scope>runtime</scope>
    </dependency>
    
    <!--druid连接池-->
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>druid-spring-boot-starter</artifactId>
        <version>1.1.10</version>
    </dependency>
    
    <!--jdbc依赖-->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-jdbc</artifactId>
    </dependency>

    在application.yml配置文件中,我们对quartz持久化方式进行声明。

    server:
      port: 10900
    
    spring:
      profiles:
        active: dev
      quartz:
        job-store-type: jdbc #持久化到数据库
        properties:
          org:
            quartz:
              datasource:
                # 新版驱动从com.mysql.jdbc.Driver变更为com.mysql.cj.jdbc.Driver
                driver-class-name: com.mysql.cj.jdbc.Driver
                # 数据源需要添加时间标准和指定编码格式解决乱码 You must configure either the server or JDBC driver (via the serverTimezone configuration property) to use a more specifc time zone value if you want to utilize time zone support.
                url: jdbc:mysql://localhost:3306/springboot?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
                username: root
                password: 1234
              scheduler:
                instancName: clusteredScheduler
                instanceId: AUTO
              jobStore:
                class: org.quartz.impl.jdbcjobstore.JobStoreTX
                driverDelegateClass: org.quartz.impl.jdbcjobstore.StdJDBCDelegate #StdJDBCDelegate说明支持集群
                tablePrefix: QRTZ_
                isClustered: true
                clusterCheckinInterval: 1000
                useProperties: false
              threadPool:
                class: org.quartz.simpl.SimpleThreadPool
                threadCount: 20
                threadPriority: 5

    这里主要就是job-store-type: jdbc,表示持久化到数据库,然后就是数据源,由于该演示项目没有其他ORM的数据源,所以这里将数据源信息定义在了quartz节点下的datasource节点,如果已经存在,可使用同一个属性配置,当然最关键的是QuartzDataSource声明。

    这里关键的是@QuartzDataSource,这个要和项目中已经存在的数据源区分开。

    //Error:EmbeddedDatabaseType class not found,Druid数据源初始化需要引入spring-jdbc依赖,JPA或mybatis依赖已经包含该依赖
    @Bean
    @QuartzDataSource
    @ConfigurationProperties(prefix = "spring.quartz.properties.org.quartz.datasource")
    DataSource quartzDataSource(){
        return DruidDataSourceBuilder.create().build();
    }

    这样持久化就已经配置好了,我们执行sql,再启动项目,启动完成后,我们可以看到数据库中已经有我们的定时调度数据了。

    源码地址:https://github.com/imyanger/springboot-project/tree/master/p25-springboot-quartz










  • 相关阅读:
    node.js 安装后怎么打开 node.js 命令框
    thinkPHP5 where多条件查询
    网站title中的图标
    第一次写博客
    Solution to copy paste not working in Remote Desktop
    The operation could not be completed. (Microsoft.Dynamics.BusinessConnectorNet)
    The package failed to load due to error 0xC0011008
    VS2013常用快捷键
    微软Dynamics AX的三层架构
    怎样在TFS(Team Foundation Server)中链接团队项目
  • 原文地址:https://www.cnblogs.com/lalalazar/p/14861696.html
Copyright © 2011-2022 走看看