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

 

转载于:https://www.cnblogs.com/yanqb/p/10615702.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值