详解SpringBoot开发案例之整合定时任务(Scheduled)

2025-05-29 0 47

来来来小伙伴们,基于上篇的邮件服务,定时任务就不单独分项目了,天然整合进了邮件服务中。

不知道,大家在工作之中,经常会用到那些定时任务去执行特定的业务,这里列举一下我在工作中曾经使用到的几种实现。

任务介绍

  1. Java自带的java.util.Timer类,这个类允许你调度一个java.util.TimerTask任务。Timer的优点在于简单易用;缺点是Timer的所有任务都是由同一个线程调度的,因此所有任务都是串行执行的。同一时间只能有一个任务在执行,前一个任务的延迟或异常都将会影响到之后的任务。这种实现已经被项目所废弃。
  2. 开源集群任务框架Quartz,这是一个功能比较强大的的调度器,适合做任务集群,解决单点故障,目前项目中在使用。
  3. Spring家族自带的Scheduled,可以将它看成一个轻量级的Quartz,而且使用起来比Quartz简单许多,适用于简单的任务,微服务使用很方便。

项目应用

创建任务

代码中,可以发现,sendMail方法上注解被注释掉了,目前我们采用的是xml配置实现的。

?

1

2

3

4

5

6

7

8

9

10

11

12

13
import org.springframework.stereotype.Component;

/**

* 统计失败邮件定时重新发送

* 创建时间 2017年7月21日

*

*/

@Component("sendMail")

public class SendMail {

//@Scheduled(cron = "0/5 * * * * ?")

public void sendMail() {

System.out.println("统计失败邮件定时重新发送开始");

}

}

配置文件

?

1

2

3

4

5

6

7

8

9
<!-- 配置任务线性池 -->

<task:executor id="executor" pool-size="5" />

<task:scheduler id="scheduler" pool-size="5"/>

<!-- 启用注解驱动的定时任务 -->

<task:annotation-driven executor="executor" scheduler="scheduler" proxy-target-class="true"/>

<task:scheduled-tasks scheduler="scheduler">

<!-- 统计失败邮件定时重新发送 -->

<task:scheduled ref="sendMail" method="sendMail" cron="0/5 * * * * ?"/>

</task:scheduled-tasks>

启动项目

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15
/**

* 启动类

* 创建时间 2017年7月19日

*

*/

@EnableAutoConfiguration

@ComponentScan(basePackages={"com.itstyle.main"})

@ImportResource({"classpath:spring-context-dubbo.xml","classpath:spring-context-task.xml"})

public class Application {

private static final Logger logger = Logger.getLogger(Application.class);

public static void main(String[] args) throws InterruptedException {

SpringApplication.run(Application.class, args);

logger.info("项目启动 ");

}

}

启动后,控制台会每5s打印”统计失败邮件定时重新发送开始”。当然Scheduled的功能不仅仅如此,我们查找源码Scheduled类,可以发现还有一些注解属性,这里就不一一为大家介绍了。总之,要养成查看源码API的习惯。

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15
@Target({ java.lang.annotation.ElementType.METHOD,

java.lang.annotation.ElementType.ANNOTATION_TYPE })

@Retention(RetentionPolicy.RUNTIME)

@Documented

@Repeatable(Schedules.class)

public @interface Scheduled {

public abstract String cron();

public abstract String zone();

public abstract long fixedDelay();

public abstract String fixedDelayString();

public abstract long fixedRate();

public abstract String fixedRateString();

public abstract long initialDelay();

public abstract String initialDelayString();

}

项目:spring-boot-mail.rar

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

原文链接:https://blog.52itstyle.com/archives/1280/?utm_source=tuicool&utm_medium=referral

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 详解SpringBoot开发案例之整合定时任务(Scheduled) https://www.kuaiidc.com/115837.html

相关文章

发表评论
暂无评论