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

相关文章:

  • 2021-09-12
  • 2021-12-06
  • 2021-07-28
  • 2021-12-15
  • 2022-12-23
  • 2021-07-07
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2021-05-25
  • 2022-12-23
  • 2022-12-23
  • 2021-07-14
  • 2021-05-22
相关资源
相似解决方案