最近一直被各种问题打断,没有静下心来去对现有问题进行深思。老样子,还是拿一个具体的问题开刀。
【问题描述】
通过springboot 创建定时任务, 创建完定时任务后,需要对定时任务进行删除,但是任务始终删除不了
删除代码如下:
@Override
public void deleteTrigger(String triggerName, String jobName, String group) {
try {
logger.debug("delete trigger {" + triggerName + "@" + group + "}");
//pause trigger
scheduler.pauseTrigger(TriggerKey.triggerKey(triggerName, group));
//delete job
scheduler.deleteJob(JobKey.jobKey(jobName, group));
scheduler.unscheduleJob(TriggerKey.triggerKey(triggerName, group));
logger.debug("trigger {" + triggerName + "@" + group + "} resumed");
} catch (SchedulerException e) {
logger.warn("delete trigger error", e);
throw new RuntimeException(e);
}
}
开始的时候,总是在想为什么删不了,查看源码,实现如下:
StdJDBCDelegate 代理类实现:
/**
* <p>
* Delete the base trigger data for a trigger.
* </p>
*
* @param conn
* the DB Connection
* @return the number of rows deleted
*/
public int deleteTrigger(Connection conn, TriggerKey triggerKey) throws SQLException {
PreparedStatement ps = null;
deleteTriggerExtension(conn, triggerKey);
try {
ps = conn.prepareStatement(rtp(DELETE_TRIGGER));
ps.setString(1, triggerKey.getName());
ps.setString(2, triggerKey.getGroup());
return ps.executeUpdate();
} finally {
closeStatement(ps);
}
}
实现Sql:
String DELETE_TRIGGER = "DELETE FROM "
+ TABLE_PREFIX_SUBST + TABLE_TRIGGERS + " WHERE "
+ COL_SCHEDULER_NAME + " = " + SCHED_NAME_SUBST
+ " AND " + COL_TRIGGER_NAME + " = ? AND " + COL_TRIGGER_GROUP + " = ?";
但是打断点,却没有执行
然后查看当时SchedulerFactoryBean 这个对象的值 是自己new的,并没有从容器中获取,导致创建的scheduler对象是null,后来改成bean 注入方式
@Bean(name = "schedulerFactoryBean")
public SchedulerFactoryBean schedulerFactory(DruidDataSource dataSource) {
SchedulerFactoryBean factory = new SchedulerFactoryBean();
//TODO 程序启动后,延迟20s执行
factory.setStartupDelay(20);
factory.setDataSource(dataSource);
factory.setQuartzProperties(quartzConfigurationProperties);
factory.setTriggers(cronTriggerFactoryBean().getObject());
return factory;
}
@Bean(name = "scheduler")
@ConditionalOnBean(SchedulerFactoryBean.class)
public Scheduler schedulerBean(SchedulerFactoryBean schedulerFactoryBean) {
schedulerFactoryBean.setTriggers(cronTriggerFactoryBean().getObject());
Scheduler scheduler = schedulerFactoryBean.getScheduler();
return scheduler;
}
当时写的时候,intellj 这块一直提示 “could not autowire” ,后来尝试启动,正常,想起来,intellj 太过智能,导致一些误报,关掉
关掉 一切正常
【结束语】
至此,该问题就解决了,使用springboot 还需要深入