Spring Boot定时器 Spring Boot定时器创建及使用解析

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

Spring Boot定时器 Spring Boot定时器创建及使用解析

阮帅   2021-01-29 我要评论

创建定时器

因为项目需要定时在后端执行任务刷新数据,不需要从前端调用接口,所以需要使用定时器。基于注解方式@Scheduled默认为单线程。

package com.ruanshuai.demo.util;

import com.ruanshuai.demo.config.ConfigConsts;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

/**
 * @author ruanshuai
 * @date 2019/10/30
 */

@Component
@EnableScheduling
public class TestSchedule {
  
  @Scheduled(fixedDelay = ConfigConsts.TEN_SECONDS)
  public void test(){
    System.out.println("定时任务执行开始!");
    System.out.println("这是一个定时任务!");
    System.out.println("定时任务执行结束!");
  }
}

其中TEN_SECONDS表示10秒,定时器任务每10秒钟自动执行一个。

各种时间表示如下:

  • 1 * 1000表示1秒;
  • 60 * 1 * 1000表示1分钟;
  • 60 * 60 * 1 * 1000表示1小时;
  • 24 * 60 * 60 * 1 * 1000表示1天;

依此类推

package com.ruanshuai.demo.config;

/**
 * @author ruanshuai
 * @date 2019/10/30
 */
public class ConfigConsts {

  public static final long TEN_SECONDS = 10 * 1 * 1000;
}

启动测试

启动项目,定时器任务在项目启动时执行一次,之后每隔10秒自动执行一次。

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们