Advertisement
Guest User

Untitled

a guest
Feb 7th, 2016
104
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 19.49 KB | None | 0 0
  1. JobDetail emailJob = JobBuilder.newJob(EMailJob.class)
  2. .withIdentity("someJobKey", "immediateEmailsGroup")
  3. .storeDurably()
  4. .build();
  5.  
  6. SimpleTrigger trigger = (SimpleTrigger) TriggerBuilder.newTrigger()
  7. .withIdentity("someTriggerKey", "immediateEmailsGroup")
  8. .startAt(fireTime)
  9. .build();
  10.  
  11. // pass initialization parameters into the job
  12. emailJob.getJobDataMap().put(NotificationConstants.MESSAGE_PARAMETERS_KEY, messageParameters);
  13. emailJob.getJobDataMap().put(NotificationConstants.RECIPIENT_KEY, recipient);
  14.  
  15. if (!scheduler.checkExists(jobKey) && scheduler.getTrigger(triggerKey) != null) {
  16. // schedule the job to run
  17. Date scheduleTime1 = scheduler.scheduleJob(emailJob, trigger);
  18. }
  19.  
  20. public class EMailJob implements Job {
  21. @Autowired
  22. private JavaMailSenderImpl mailSenderImpl;
  23.  
  24. public EMailJob() {
  25. }
  26. public void execute(JobExecutionContext context)
  27. throws JobExecutionException {
  28. ....
  29. try {
  30. mailSenderImpl.send(mimeMessage);
  31. } catch (MessagingException e) {
  32. ....
  33. throw new JobExecutionException("EMailJob failed: " + jobKey.getName(), e);
  34. }
  35.  
  36. logger.info("EMailJob finished OK");
  37.  
  38. }
  39.  
  40. @Autowired
  41. private JavaMailSenderImpl mailSenderImpl;
  42.  
  43. 2011-08-15 14:16:38,687 [main] INFO org.springframework.context.support.GenericApplicationContext - Bean 'org.springframework.security.access.expression.method.DefaultMethodSecurityExpressionHandler#0' is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
  44. 2011-08-15 14:16:38,734 [main] INFO org.springframework.beans.factory.support.DefaultListableBeanFactory - Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@1328c7a: defining beans [...]; root of factory hierarchy
  45. 2011-08-15 14:16:39,734 [main] INFO com.cambridgedata.notifications.EMailJob - EMailJob() - initializing ...
  46. 2011-08-15 14:16:39,937 [main] INFO org.springframework.security.access.intercept.aopalliance.MethodSecurityInterceptor - Validated configuration attributes
  47. 2011-08-15 14:16:40,078 [main] INFO org.springframework.security.web.access.intercept.FilterSecurityInterceptor - Validated configuration attributes
  48. 2011-08-15 14:16:40,296 [main] INFO org.springframework.jdbc.datasource.init.ResourceDatabasePopulator - Executing SQL script from class path resource ...
  49. 2011-08-15 14:17:14,031 [main] INFO com.mchange.v2.log.MLog - MLog clients using log4j logging.
  50. 2011-08-15 14:17:14,109 [main] INFO com.mchange.v2.c3p0.C3P0Registry - Initializing c3p0-0.9.1.1 [built 15-March-2007 01:32:31; debug? true; trace: 10]
  51. 2011-08-15 14:17:14,171 [main] INFO org.quartz.core.SchedulerSignalerImpl - Initialized Scheduler Signaller of type: class org.quartz.core.SchedulerSignalerImpl
  52. 2011-08-15 14:17:14,171 [main] INFO org.quartz.core.QuartzScheduler - Quartz Scheduler v.2.0.1 created.
  53. 2011-08-15 14:17:14,187 [main] INFO org.quartz.impl.jdbcjobstore.JobStoreTX - Using thread monitor-based data access locking (synchronization).
  54. 2011-08-15 14:17:14,187 [main] INFO org.quartz.impl.jdbcjobstore.JobStoreTX - JobStoreTX initialized.
  55. 2011-08-15 14:17:14,187 [main] INFO org.quartz.core.QuartzScheduler - Scheduler meta-data: Quartz Scheduler (v2.0.1) 'NotificationsScheduler' with instanceId 'NON_CLUSTERED'
  56. Scheduler class: 'org.quartz.core.QuartzScheduler' - running locally.
  57. NOT STARTED.
  58. Currently in standby mode.
  59. Number of jobs executed: 0
  60. Using thread pool 'org.quartz.simpl.SimpleThreadPool' - with 3 threads.
  61. Using job-store 'org.quartz.impl.jdbcjobstore.JobStoreTX' - which supports persistence. and is not clustered.
  62.  
  63. 2011-08-15 14:17:14,187 [main] INFO org.quartz.impl.StdSchedulerFactory - Quartz scheduler 'NotificationsScheduler' initialized from the specified file : 'spring/quartz.properties' from the class resource path.
  64. 2011-08-15 14:17:14,187 [main] INFO org.quartz.impl.StdSchedulerFactory - Quartz scheduler version: 2.0.1
  65. 2011-08-15 14:17:14,234 [main] INFO com.mchange.v2.c3p0.impl.AbstractPoolBackedDataSource - Initializing c3p0 pool... com.mchange.v2.c3p0.ComboPooledDataSource [ acquireIncrement -> 3, acquireRetryAttempts -> 30, acquireRetryDelay -> 1000, autoCommitOnClose -> false, automaticTestTable -> null, breakAfterAcquireFailure -> false, checkoutTimeout -> 0, connectionCustomizerClassName -> null, connectionTesterClassName -> com.mchange.v2.c3p0.impl.DefaultConnectionTester, dataSourceName -> 2sajb28h1lcabf28k3nr1|13af084, debugUnreturnedConnectionStackTraces -> false, description -> null, driverClass -> com.mysql.jdbc.Driver, factoryClassLocation -> null, forceIgnoreUnresolvedTransactions -> false, identityToken -> 2sajb28h1lcabf28k3nr1|13af084, idleConnectionTestPeriod -> 50, initialPoolSize -> 3, jdbcUrl -> jdbc:mysql://localhost:3306/2010rewrite2, lastAcquisitionFailureDefaultUser -> null, maxAdministrativeTaskTime -> 0, maxConnectionAge -> 0, maxIdleTime -> 0, maxIdleTimeExcessConnections -> 0, maxPoolSize -> 5, maxStatements -> 0, maxStatementsPerConnection -> 120, minPoolSize -> 1, numHelperThreads -> 3, numThreadsAwaitingCheckoutDefaultUser -> 0, preferredTestQuery -> select 0 from dual, properties -> {user=******, password=******}, propertyCycle -> 0, testConnectionOnCheckin -> true, testConnectionOnCheckout -> false, unreturnedConnectionTimeout -> 0, usesTraditionalReflectiveProxies -> false ]
  66. 2011-08-15 14:17:14,312 [main] INFO org.quartz.impl.jdbcjobstore.JobStoreTX - Freed 0 triggers from 'acquired' / 'blocked' state.
  67. 2011-08-15 14:17:14,328 [main] INFO org.quartz.impl.jdbcjobstore.JobStoreTX - Recovering 0 jobs that were in-progress at the time of the last shut-down.
  68. 2011-08-15 14:17:14,328 [main] INFO org.quartz.impl.jdbcjobstore.JobStoreTX - Recovery complete.
  69. 2011-08-15 14:17:14,328 [main] INFO org.quartz.impl.jdbcjobstore.JobStoreTX - Removed 0 'complete' triggers.
  70. 2011-08-15 14:17:14,328 [main] INFO org.quartz.impl.jdbcjobstore.JobStoreTX - Removed 0 stale fired job entries.
  71. 2011-08-15 14:17:14,328 [main] INFO org.quartz.core.QuartzScheduler - Scheduler NotificationsScheduler_$_NON_CLUSTERED started.
  72. 2011-08-15 14:17:14,515 [NotificationsScheduler_QuartzSchedulerThread] INFO com.cambridgedata.notifications.EMailJob - EMailJob() - initializing ...
  73.  
  74. <bean id="jobFactoryBean" class="org.springframework.scheduling.quartz.SpringBeanJobFactory">
  75. </bean>
  76.  
  77. <bean id="schedulerFactoryBean" class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
  78. <property name="configLocation" value="classpath:spring/quartz.properties"/>
  79. <property name="jobFactory" ref="jobFactoryBean"/>
  80. </bean>
  81.  
  82. @PostConstruct
  83. public void initNotificationScheduler() {
  84. try {
  85. //sf = new StdSchedulerFactory("spring/quartz.properties");
  86. //scheduler = sf.getScheduler();
  87.  
  88. scheduler = schedulerFactoryBean.getScheduler();
  89. scheduler.start();
  90. ....
  91.  
  92. 2011-08-15 21:49:42,968 [main] INFO org.springframework.scheduling.quartz.SchedulerFactoryBean - Loading Quartz config from [class path resource [spring/quartz.properties]]
  93. 2011-08-15 21:49:43,031 [main] INFO com.mchange.v2.log.MLog - MLog clients using log4j logging.
  94. 2011-08-15 21:49:43,109 [main] INFO com.mchange.v2.c3p0.C3P0Registry - Initializing c3p0-0.9.1.1 [built 15-March-2007 01:32:31; debug? true; trace: 10]
  95. 2011-08-15 21:49:43,187 [main] INFO org.quartz.core.SchedulerSignalerImpl - Initialized Scheduler Signaller of type: class org.quartz.core.SchedulerSignalerImpl
  96. 2011-08-15 21:49:43,187 [main] INFO org.quartz.core.QuartzScheduler - Quartz Scheduler v.2.0.1 created.
  97. 2011-08-15 21:49:43,187 [main] INFO org.quartz.impl.jdbcjobstore.JobStoreTX - Using thread monitor-based data access locking (synchronization).
  98. 2011-08-15 21:49:43,187 [main] INFO org.quartz.impl.jdbcjobstore.JobStoreTX - JobStoreTX initialized.
  99. 2011-08-15 21:49:43,187 [main] INFO org.quartz.core.QuartzScheduler - Scheduler meta-data: Quartz Scheduler (v2.0.1) 'schedulerFactoryBean' with instanceId 'NON_CLUSTERED'
  100. Scheduler class: 'org.quartz.core.QuartzScheduler' - running locally.
  101. NOT STARTED.
  102. Currently in standby mode.
  103. Number of jobs executed: 0
  104. Using thread pool 'org.quartz.simpl.SimpleThreadPool' - with 3 threads.
  105. Using job-store 'org.quartz.impl.jdbcjobstore.JobStoreTX' - which supports persistence. and is not clustered.
  106.  
  107. 2011-08-15 21:49:43,187 [main] INFO org.quartz.impl.StdSchedulerFactory - Quartz scheduler 'schedulerFactoryBean' initialized from an externally provided properties instance.
  108. 2011-08-15 21:49:43,187 [main] INFO org.quartz.impl.StdSchedulerFactory - Quartz scheduler version: 2.0.1
  109. 2011-08-15 21:49:43,187 [main] INFO org.quartz.core.QuartzScheduler - JobFactory set to: org.springframework.scheduling.quartz.SpringBeanJobFactory@566633
  110. 2011-08-15 21:49:43,265 [main] INFO com.mchange.v2.c3p0.impl.AbstractPoolBackedDataSource - Initializing c3p0 pool... com.mchange.v2.c3p0.ComboPooledDataSource [ acquireIncrement -> 3, acquireRetryAttempts -> 30, acquireRetryDelay -> 1000, autoCommitOnClose -> false, automaticTestTable -> null, breakAfterAcquireFailure -> false, checkoutTimeout -> 0, connectionCustomizerClassName -> null, connectionTesterClassName -> com.mchange.v2.c3p0.impl.DefaultConnectionTester, dataSourceName -> 1hge13f8h1lsg7py1rg0iu0|1956391, debugUnreturnedConnectionStackTraces -> false, description -> null, driverClass -> com.mysql.jdbc.Driver, factoryClassLocation -> null, forceIgnoreUnresolvedTransactions -> false, identityToken -> 1hge13f8h1lsg7py1rg0iu0|1956391, idleConnectionTestPeriod -> 50, initialPoolSize -> 3, jdbcUrl -> jdbc:mysql://localhost:3306/2010rewrite2, lastAcquisitionFailureDefaultUser -> null, maxAdministrativeTaskTime -> 0, maxConnectionAge -> 0, maxIdleTime -> 0, maxIdleTimeExcessConnections -> 0, maxPoolSize -> 5, maxStatements -> 0, maxStatementsPerConnection -> 120, minPoolSize -> 1, numHelperThreads -> 3, numThreadsAwaitingCheckoutDefaultUser -> 0, preferredTestQuery -> select 0 from dual, properties -> {user=******, password=******}, propertyCycle -> 0, testConnectionOnCheckin -> true, testConnectionOnCheckout -> false, unreturnedConnectionTimeout -> 0, usesTraditionalReflectiveProxies -> false ]
  111. 2011-08-15 21:49:43,343 [main] INFO org.quartz.impl.jdbcjobstore.JobStoreTX - Freed 0 triggers from 'acquired' / 'blocked' state.
  112. 2011-08-15 21:49:43,359 [main] INFO org.quartz.impl.jdbcjobstore.JobStoreTX - Recovering 0 jobs that were in-progress at the time of the last shut-down.
  113. 2011-08-15 21:49:43,359 [main] INFO org.quartz.impl.jdbcjobstore.JobStoreTX - Recovery complete.
  114. 2011-08-15 21:49:43,359 [main] INFO org.quartz.impl.jdbcjobstore.JobStoreTX - Removed 0 'complete' triggers.
  115. 2011-08-15 21:49:43,359 [main] INFO org.quartz.impl.jdbcjobstore.JobStoreTX - Removed 0 stale fired job entries.
  116. 2011-08-15 21:49:43,359 [main] INFO org.quartz.core.QuartzScheduler - Scheduler schedulerFactoryBean_$_NON_CLUSTERED started.
  117. 2011-08-15 21:49:43,562 [schedulerFactoryBean_QuartzSchedulerThread] ERROR org.quartz.core.ErrorLogger - An error occured instantiating job to be executed. job= 'immediateEmailsGroup.DEFAULT.jobFor_1000new1'
  118. org.quartz.SchedulerException: Problem instantiating class 'com.cambridgedata.notifications.EMailJob' - [See nested exception: java.lang.AbstractMethodError: org.springframework.scheduling.quartz.SpringBeanJobFactory.newJob(Lorg/quartz/spi/TriggerFiredBundle;Lorg/quartz/Scheduler;)Lorg/quartz/Job;]
  119. at org.quartz.core.JobRunShell.initialize(JobRunShell.java:141)
  120. at org.quartz.core.QuartzSchedulerThread.run(QuartzSchedulerThread.java:381)
  121. Caused by: java.lang.AbstractMethodError: org.springframework.scheduling.quartz.SpringBeanJobFactory.newJob(Lorg/quartz/spi/TriggerFiredBundle;Lorg/quartz/Scheduler;)Lorg/quartz/Job;
  122. at org.quartz.core.JobRunShell.initialize(JobRunShell.java:134)
  123.  
  124. import org.quartz.spi.TriggerFiredBundle;
  125. import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
  126. import org.springframework.context.ApplicationContext;
  127. import org.springframework.context.ApplicationContextAware;
  128. import org.springframework.scheduling.quartz.SpringBeanJobFactory;
  129.  
  130. public final class AutowiringSpringBeanJobFactory extends SpringBeanJobFactory implements
  131. ApplicationContextAware {
  132.  
  133. private transient AutowireCapableBeanFactory beanFactory;
  134.  
  135. @Override
  136. public void setApplicationContext(final ApplicationContext context) {
  137. beanFactory = context.getAutowireCapableBeanFactory();
  138. }
  139.  
  140. @Override
  141. protected Object createJobInstance(final TriggerFiredBundle bundle) throws Exception {
  142. final Object job = super.createJobInstance(bundle);
  143. beanFactory.autowireBean(job);
  144. return job;
  145. }
  146. }
  147.  
  148. @Bean
  149. public SchedulerFactoryBean quartzScheduler() {
  150. SchedulerFactoryBean quartzScheduler = new SchedulerFactoryBean();
  151.  
  152. ...
  153.  
  154. AutowiringSpringBeanJobFactory jobFactory = new AutowiringSpringBeanJobFactory();
  155. jobFactory.setApplicationContext(applicationContext);
  156. quartzScheduler.setJobFactory(jobFactory);
  157.  
  158. ...
  159.  
  160. return quartzScheduler;
  161. }
  162.  
  163. <bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
  164. <propertyy name="triggers">
  165. <list>
  166. <ref bean="simpleTrigger"/>
  167. </list>
  168. </property>
  169. <property name="applicationContextSchedulerContextKey">
  170. <value>applicationContext</value>
  171. </property>
  172.  
  173. appCtx = (ApplicationContext)context.getScheduler().getContext().get("applicationContextSchedulerContextKey");
  174.  
  175. <bean name="myJobDetail" class="org.springframework.scheduling.quartz.JobDetailBean">
  176. <property name="jobClass"
  177. value="my.cool.class.myCoolJob" />
  178. <property name="jobDataAsMap">
  179. <map>
  180. <entry key="myBean" value-ref="myBean" />
  181. </map>
  182. </property>
  183. </bean>
  184.  
  185. public void executeInternal(JobExecutionContext context)
  186.  
  187. <bean id="quartzScheduler" class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
  188. <property name="configLocation" value="classpath:spring/quartz.properties"/>
  189. <property name="jobFactory">
  190. <bean class="org.springframework.scheduling.quartz.SpringBeanJobFactory" />
  191. </property>
  192. <property name="schedulerContextAsMap">
  193. <map>
  194. <entry key="mailService" value-ref="mailService" />
  195. </map>
  196. </property>
  197. </bean>
  198. <bean id="jobTriggerFactory"
  199. class="org.springframework.beans.factory.config.ObjectFactoryCreatingFactoryBean">
  200. <property name="targetBeanName">
  201. <idref local="jobTrigger" />
  202. </property>
  203. </bean>
  204. <bean id="jobTrigger" class="org.springframework.scheduling.quartz.SimpleTriggerBean"
  205. scope="prototype">
  206. <property name="group" value="myJobs" />
  207. <property name="description" value="myDescription" />
  208. <property name="repeatCount" value="0" />
  209. </bean>
  210.  
  211. <bean id="jobDetailFactory"
  212. class="org.springframework.beans.factory.config.ObjectFactoryCreatingFactoryBean">
  213. <property name="targetBeanName">
  214. <idref local="jobDetail" />
  215. </property>
  216. </bean>
  217.  
  218. <bean id="jobDetail" class="org.springframework.scheduling.quartz.JobDetailBean"
  219. scope="prototype">
  220. <property name="jobClass" value="com.cambridgedata.notifications.EMailJob" />
  221. <property name="volatility" value="false" />
  222. <property name="durability" value="false" />
  223. <property name="requestsRecovery" value="true" />
  224. </bean>
  225. <bean id="notificationScheduler" class="com.cambridgedata.notifications.NotificationScheduler">
  226. <constructor-arg ref="quartzScheduler" />
  227. <constructor-arg ref="jobDetailFactory" />
  228. <constructor-arg ref="jobTriggerFactory" />
  229. </bean>
  230.  
  231. public void executeInternal(JobExecutionContext context)
  232. throws JobExecutionException {
  233.  
  234. logger.info("EMailJob started ...");
  235. ....
  236. SchedulerContext schedulerContext = null;
  237. try {
  238. schedulerContext = context.getScheduler().getContext();
  239. } catch (SchedulerException e1) {
  240. e1.printStackTrace();
  241. }
  242. MailService mailService = (MailService)schedulerContext.get("mailService");
  243. ....
  244.  
  245. public NotificationScheduler(final Scheduler scheduler,
  246. final ObjectFactory<JobDetail> jobDetailFactory,
  247. final ObjectFactory<SimpleTrigger> jobTriggerFactory) {
  248. this.scheduler = scheduler;
  249. this.jobDetailFactory = jobDetailFactory;
  250. this.jobTriggerFactory = jobTriggerFactory;
  251. ...
  252. // create a trigger
  253. SimpleTrigger trigger = jobTriggerFactory.getObject();
  254. trigger.setRepeatInterval(0L);
  255. trigger.setStartTime(new Date());
  256.  
  257. // create job details
  258. JobDetail emailJob = jobDetailFactory.getObject();
  259.  
  260. emailJob.setName("new name");
  261. emailJob.setGroup("immediateEmailsGroup");
  262. ...
  263.  
  264. ApplicationContext springContext =
  265.  
  266. WebApplicationContextUtils.getWebApplicationContext(ContextLoaderListener .getCurrentWebApplicationContext().getServletContext());
  267.  
  268. Bean bean = (Bean) springContext.getBean("beanName");
  269.  
  270. bean.method();
  271.  
  272. public class NotificationScheduler {
  273.  
  274. private SchedulerFactory sf;
  275. private Scheduler scheduler;
  276.  
  277. @PostConstruct
  278. public void initNotificationScheduler() {
  279. try {
  280. sf = new StdSchedulerFactory("spring/quartz.properties");
  281. scheduler = sf.getScheduler();
  282. scheduler.start();
  283. // test out sending a notification at startup, prepare some parameters...
  284. this.scheduleImmediateNotificationJob(messageParameters, recipients);
  285. try {
  286. // wait 20 seconds to show jobs
  287. logger.info("sleeping...");
  288. Thread.sleep(40L * 1000L);
  289. logger.info("finished sleeping");
  290. // executing...
  291. } catch (Exception ignore) {
  292. }
  293.  
  294. } catch (SchedulerException e) {
  295. e.printStackTrace();
  296. throw new RuntimeException("NotificationScheduler failed to retrieve a Scheduler instance: ", e);
  297. }
  298. }
  299.  
  300.  
  301. public void scheduleImmediateNotificationJob(){
  302. try {
  303. JobKey jobKey = new JobKey("key");
  304. Date fireTime = DateBuilder.futureDate(delayInSeconds, IntervalUnit.SECOND);
  305. JobDetail emailJob = JobBuilder.newJob(EMailJob.class)
  306. .withIdentity(jobKey.toString(), "immediateEmailsGroup")
  307. .build();
  308.  
  309. TriggerKey triggerKey = new TriggerKey("triggerKey");
  310. SimpleTrigger trigger = (SimpleTrigger) TriggerBuilder.newTrigger()
  311. .withIdentity(triggerKey.toString(), "immediateEmailsGroup")
  312. .startAt(fireTime)
  313. .build();
  314.  
  315. // schedule the job to run
  316. Date scheduleTime1 = scheduler.scheduleJob(emailJob, trigger);
  317. } catch (SchedulerException e) {
  318. logger.error("error scheduling job: " + e.getMessage(), e);
  319. e.printStackTrace();
  320. }
  321. }
  322.  
  323. @PreDestroy
  324. public void cleanup(){
  325. sf = null;
  326. try {
  327. scheduler.shutdown();
  328. } catch (SchedulerException e) {
  329. e.printStackTrace();
  330. }
  331. }
  332.  
  333. @Component
  334. public class EMailJob implements Job {
  335. @Autowired
  336. private JavaMailSenderImpl mailSenderImpl;
  337. ... }
  338.  
  339. ...
  340. <context:property-placeholder location="classpath:spring/*.properties" />
  341. <context:spring-configured/>
  342. <context:component-scan base-package="com.mybasepackage">
  343. <context:exclude-filter expression="org.springframework.stereotype.Controller"
  344. type="annotation" />
  345. </context:component-scan>
  346. <bean id="mailSenderImpl" class="org.springframework.mail.javamail.JavaMailSenderImpl">
  347. <property name="host" value="${mail.host}"/>
  348. <property name="port" value="${mail.port}"/>
  349. ...
  350. </bean>
  351. <bean id="notificationScheduler" class="com.mybasepackage.notifications.NotificationScheduler">
  352. </bean>
  353.  
  354. AutowiringSpringBeanJobFactory extends SpringBeanJobFactory
  355.  
  356. "org.springframework:spring-context-support:4..."
  357.  
  358. "org.springframework:spring-support:2..."
  359.  
  360. @Override
  361. public Job newJob(TriggerFiredBundle bundle, Scheduler scheduler)
  362.  
  363. @Override
  364. protected Object createJobInstance(final TriggerFiredBundle bundle)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement