• SpringMVC基于注解方式的quartz


    项目框架: SpringMVC、MyBatis、JSP

    1. 首先配置spring.xml文件

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans" 
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
           xmlns:context="http://www.springframework.org/schema/context"
           xmlns:task="http://www.springframework.org/schema/task"
           xsi:schemaLocation="http://www.springframework.org/schema/beans
                    http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
                    http://www.springframework.org/schema/context
                    http://www.springframework.org/schema/context/spring-context-4.2.xsd
                    http://www.springframework.org/schema/task
                    http://www.springframework.org/schema/task/spring-task-3.1.xsd">
    
        <!-- 注解定时任务 -->
        <task:annotation-driven/>

    2. 配置定时任务类

    @Component
    public class MessageSendService {
    
        /**
         * 记录日志类
         */
        public Log logger = LogFactory.getLog(this.getClass());
    
        /**
         * 定时任务方法
         */
        @Scheduled(cron = "0/10 * * * * ? ")
        public void send(){
            logger.info("start.....");
        }
    
    }

     @Component 注解是让Spring可以扫描到并初始化,第一步的配置就是做这个用的

     @Scheduled 注解是配置定时任务的执行时间,上面的配置是让定时任务每10执行一次send()方法

    3. 实际的项目中定时任务的执行时间可能要在配置文件中配置,就需要用到另一个注解 @PropertySource

    @Component
    @PropertySource(value="classpath:application.properties")
    public class MessageSendService {
    
        /**
         * 记录日志类
         */
        public Log logger = LogFactory.getLog(this.getClass());
    
        /**
         * 方法
         */
        @Scheduled(cron = "${jobs.message}")
        public void send(){
            logger.info("start.....");
            
        }
    
    }

    @PropertySource 指定配置文件的位置,和配置文件的名称

    @Scheduled 注解做相应的修改

    4. application.properties 文件配置

    ## 轮询时间配置
    jobs.message=0/10 * * * * ?

    这个定时任务时间配置和linux的crontab差不多

    5. Scheduled 参数1

    @Scheduled(fixedDelay = 5000)
    public void doSomething() { 
        // something that should execute periodically
    }

    这个方法将以一个固定延迟时间5秒钟调用一次执行,这个周期是以上一个调用任务的完成时间为基准,在上一个任务完成之后,5s后再次执行

    当方法执行超过5秒,下一个轮询发现有正在执行的方法,直接跳过

    6. Scheduled 参数2

    @Scheduled(fixedRate = 5000)
    public void doSomething() { 
        // something that should execute periodically
    }

    这个方法将以一个固定速率5s来调用一次执行,这个周期是以上一个任务开始时间为基准,从上一任务开始执行后5s再次调用

    当方法执行时间超过5秒,下一个轮询会阻塞,上一个任务执行完成,立即执行此次轮询方法

  • 相关阅读:
    识别IE11浏览器
    国庆过后老革命
    有些东西再忙也要做
    云计算
    SVN下Update出现代码文件删除状态问题
    如何避免历史回退到登录页面
    CodeSmith连Oracle
    NHibernate直接执行SQL进行插入
    nhibernate实体类主键ID赋值问题
    NHibernate不支持复杂的linq,就一定要用DataTable这么低级吗
  • 原文地址:https://www.cnblogs.com/liuchao102/p/6064819.html
Copyright © 2020-2023  润新知