Spring Boot中如何配置并运用定时任务机制?

2026-05-24 09:382阅读0评论SEO教程
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计379个文字,预计阅读时间需要2分钟。

Spring Boot中如何配置并运用定时任务机制?

创建定时器+由于项目需求需要在后端执行任务刷新数据,无需从前端调用接口,因此需要使用定时器。基于注解方式@Scheduled,默认为单线程。+package+com.ruanshuai.demo.util;+import+com.ruanshua+。

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秒自动执行一次。

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

本文共计379个文字,预计阅读时间需要2分钟。

Spring Boot中如何配置并运用定时任务机制?

创建定时器+由于项目需求需要在后端执行任务刷新数据,无需从前端调用接口,因此需要使用定时器。基于注解方式@Scheduled,默认为单线程。+package+com.ruanshuai.demo.util;+import+com.ruanshua+。

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秒自动执行一次。

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