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

创建定时器

因为项目需要定时在后端执行任务刷新数据,不需要从前端调用接口,所以需要使用定时器。基于注解方式@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秒自动执行一次。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。