码迷,mamicode.com
首页 > 微信 > 详细

微信公众号的SpringBoot+Quartz的定时任务Demo

时间:2018-07-05 14:56:09      阅读:237      评论:0      收藏:0      [点我收藏+]

标签:tst   return   autowired   format   tac   void   driver   慕课   ebean   

技术分享图片
技术分享图片
技术分享图片
技术分享图片

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
来源:慕课网

微信公众号的SpringBoot+Quartz的定时任务Demo

标签:tst   return   autowired   format   tac   void   driver   慕课   ebean   

原文地址:https://www.cnblogs.com/yhtboke/p/9267970.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!