zoukankan      html  css  js  c++  java
  • Spring项目定时任务

    最近某协会网站有个需求:显示当天访问量,很明显需要做俩步;一个是访问请求量的显示,一个需要每天00点恢复访问次数为0

    所以需要做个定时任务:每天00点更新;

    注解用法Spring配置:

       1.在spring-servlet.xml文件中加入task的命名空间;2.使用task配置扫描注解;3.使用@Scheduled(cron = "时间格式串")

    xmlns:task="http://www.springframework.org/schema/task"
    xsi:schemaLocation="http://www.springframework.org/schema/task
            http://www.springframework.org/schema/task/spring-task-4.0.xsd"
    <!-- 定时任务 -->
        <task:annotation-driven scheduler="qbScheduler" mode="proxy"/>  
        <task:scheduler id="qbScheduler" />  
     @Scheduled(cron = "0/5 * * * * ?")  //每隔5秒执行一次定时任务
        public void consoleInfo(){
            System.out.println("定时任务");
        }

    注解用法SpringBoot配置:

     在项目中,导入依赖:

    <dependencies>
      <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
      </dependency>
      <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
      </dependency>
      <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <optional>true</optional>
      </dependency>
      <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
      </dependency>
    </dependencies>

    创建任务类:

    @Slf4j
    @Component
    public class ScheduledService {

      @Scheduled(cron = "0/5 * * * * *")
      public void scheduled(){
        log.info("=====>>>>>使用cron {}",System.currentTimeMillis());
      }
      @Scheduled(fixedRate = 5000)
      public void scheduled1() {
        log.info("=====>>>>>使用fixedRate{}", System.currentTimeMillis());
      }
      @Scheduled(fixedDelay = 5000)
      public void scheduled2() {
        log.info("=====>>>>>fixedDelay{}",System.currentTimeMillis());
      }
    }

  • 相关阅读:
    【LeetCode每日一题】2020.6.9 面试题46. 把数字翻译成字符串
    【NOIP2017提高A组模拟9.17】信仰是为了虚无之人
    【NOIP2017提高A组模拟9.17】猫
    【NOIP2017提高A组模拟9.17】组合数问题
    JZOJ 11.21 提高B组反思
    【NOIP2017提高A组模拟9.12】Arrays and Palindrome
    JZOJ【NOIP2013模拟联考14】隐藏指令
    JZOJ 11.14 提高B组反思
    CSP2020复赛游记
    JZOJ 【NOIP2017提高A组模拟9.14】捕老鼠
  • 原文地址:https://www.cnblogs.com/yanqb/p/10615702.html
Copyright © 2011-2022 走看看