微信公眾號的SpringBoot+Quartz的定時任務Demo
阿新 • • 發佈:2018-07-05
info extend 實現 err 微信 我們 url led noi
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