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());
      }
}
 
                    
                     
                    
                 
                    
                
 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号