微信公众号的SpringBoot+Quartz的定时任务Demo
SpringBoot整合quartz并不难,难在普通类实现了Job接口后等于实例化交给quartz,不受Spring管理,则service层等等其他依赖的注入将无法注入,这也是难点之一。
解决方法:
@Component
public class MyJobFactory extends AdaptableJobFactory {
@Autowired
private AutowireCapableBeanFactory capableBeanFactory;
@Override
protected Object createJobInstance(TriggerFiredBundle bundle) throws Exception {
// 调用父类的方法
Object jobInstance = super.createJobInstance(bundle);
// 进行注入
capableBeanFactory.autowireBean(jobInstance);
return jobInstance;
}
}
以上可以解决quartz的job无法注入的依赖而导致空指针的异常。
另外job类我们可以写一个逻辑方法将灵活的调用我们的定时任务。
//第一个参数是要实现调度的类,第二个是执行的时间。第三个是传递的参数
public interface QuartzService {
Map<String,Object> eventSetSuccess(Class <? extends Job> klass, Date date, NoticeDTO noticeDTO) throws SchedulerException;
}
以下是需要调用的类:(这样可以根据您的喜好只需要将相关的依赖和数值传进来就可以很方便的调用)
public class QuartEventDemo implements Job,Serializable{ //只需建立一个类,然后将需要做的事注入进来就行
private NoticeDTO noticeDTO = new NoticeDTO();
@Autowired
private PushMessageService pushMessageService; //注入失败?(已搞定)
@Override
public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
JobDataMap jobDetail = jobExecutionContext.getTrigger().getJobDataMap();
String openid = (String) jobDetail.get("openid");
String createTime = (String) jobDetail.get("createTime");
String endTime = (String) jobDetail.get("endTime");
String eventContent = (String) jobDetail.get("eventContent");
try {
noticeDTO.setCreateTime(format.parse(createTime));
noticeDTO.setEndTime(format.parse(endTime));
}catch (Exception e){
e.printStackTrace();
}
noticeDTO.setOpenid(openid);
noticeDTO.setEventContent(eventContent);
log.info("【传值是否成功】noticeDTO={}",noticeDTO);
pushMessageService.noiteEvent(noticeDTO);
}
}
配置文件:
server:
context-path: /quartzDemo
port: 80
spring:
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://127.0.0.1:3306/meetingsign?useUnicode=true&characterEncoding=utf8
username: root
password: ******
jpa:
hibernate:
ddl-auto: update
show-sql: true
wechat:
mpAppId: *******微信公众号的mpAppId
mpAppSecret:********微信公众号的mpAppSecret
quartzDemo:
quartz:这个是填写项目的域名
作者:
链接:http://www.imooc.com/article/20532
来源:慕课网
标签:
spring boot
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Java 中堆内存和栈内存上的数据分布和特点
· 开发中对象命名的一点思考
· .NET Core内存结构体系(Windows环境)底层原理浅谈
· C# 深度学习:对抗生成网络(GAN)训练头像生成模型
· .NET 适配 HarmonyOS 进展
· 如何给本地部署的DeepSeek投喂数据,让他更懂你
· 超详细,DeepSeek 接入PyCharm实现AI编程!(支持本地部署DeepSeek及官方Dee
· 用 DeepSeek 给对象做个网站,她一定感动坏了
· .NET 8.0 + Linux 香橙派,实现高效的 IoT 数据采集与控制解决方案
· DeepSeek处理自有业务的案例:让AI给你写一份小众编辑器(EverEdit)的语法着色文件
2016-07-05 mysql最大连接数
2016-07-05 ehcache 缓存
2016-07-05 servlet
2016-07-05 软考