spring task+spring事件实现定时任务+事件监听demo
spring task+spring事件实现定时任务+事件监听demo
本案例就是利用上述技术搭建的简单demo,使用的maven工程
1、工程结构界面
本工程是基于maven管理实现的,没有使用任何maven模板,具体代码地址在文章的最后。
2、定时任务
2.1 创建定时任务
package com.li.timer;
import com.li.event.RedBaoSuccessEvent;
import com.li.redbao.service.RedBao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.util.Date;
/**
* 事件源
* */
@Component
public class SendRedBao implements ApplicationEventPublisherAware {
@Autowired
private RedBao redBao;
@Autowired
private ApplicationEventPublisher applicationEventPublisher;
/**
* 定时任务,每五秒执行一次
* */
@Scheduled(cron = "0/5 * * * * ? ")
public void SendRedBao(){
System.out.println("红包发送成功!!!---------"+new Date());
//发布事件
applicationEventPublisher.publishEvent(new RedBaoSuccessEvent(this,redBao));
}
/**
* 事件发布器
* */
@Override
public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
this.applicationEventPublisher=applicationEventPublisher;
}
}
其中定时任务方法只是如下截图部分
其中
@Scheduled(cron = "0/5 * * * * ? ")
是对定时任务的时间进行设置的,cron是一种表达式,可以灵活的对定时任务进行设置。cron表达式在线可以生成,网址为https://cron.qqe2.com/
2.2开始定时任务
加上这个注解才会才会开启定时任务,否则不会执行。
3、spring事件监听
3.1 spring事件
spring事件发送监听涉及3个部分
(1)ApplicationEvent:表示事件本身,自定义事件需要继承该类,可以用来传递数据,比如上述操作,我们需要将用户的邮箱地址传给事件监听器.
(2)ApplicationEventPublisherAware:事件发送器,通过实现这个接口,来触发事件.
(3)ApplicationListener:事件监听器接口,事件的业务逻辑封装在监听器里面.
(4)事件源:就是谁触发了事件的产生。
3.2 执行流程图
4、代码部分
4.1事件源—发红包业务
4.2事件—发红包成功事件
4.2事件监听器
下面这个监听器是基于spring boot注解实现的
和上面是一样的,只是实现方式不同而已。
至此,全部的实现过程结束,码云代码地址如下码云地址