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());
      }
    }

  • 相关阅读:
    vuejs计算属性和侦听器
    vuejs属性绑定和双向绑定
    vuejs数据和事件
    vuejs挂载点,模板与实例的关系
    vuejs组件的重要选项
    vue开发环境搭建
    vuejs课程简介及框架简介
    SubString
    线性筛约数和函数
    [国家集训队]Tree II
  • 原文地址:https://www.cnblogs.com/yanqb/p/10615702.html
Copyright © 2011-2022 走看看