extract spring-scheduling module

This commit is contained in:
Denis
2019-08-31 15:39:30 +02:00
parent f47704e89d
commit 9fd2fb32ca
28 changed files with 42 additions and 4 deletions

View File

@@ -0,0 +1,5 @@
### Relevant articles:
- [A Guide to the Spring Task Scheduler](http://www.baeldung.com/spring-task-scheduler)
- [Guide to Spring Retry](http://www.baeldung.com/spring-retry)
- [How To Do @Async in Spring](http://www.baeldung.com/spring-async)

36
spring-scheduling/pom.xml Normal file
View File

@@ -0,0 +1,36 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>spring-scheduling</artifactId>
<version>0.1-SNAPSHOT</version>
<name>spring-scheduling</name>
<packaging>war</packaging>
<parent>
<artifactId>parent-boot-2</artifactId>
<groupId>com.baeldung</groupId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../parent-boot-2</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.retry</groupId>
<artifactId>spring-retry</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
</project>

View File

@@ -0,0 +1,18 @@
package com.baeldung.scheduling;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component
@EnableAsync
public class ScheduledFixedRateExample {
@Async
@Scheduled(fixedRate = 1000)
public void scheduleFixedRateTaskAsync() throws InterruptedException {
System.out.println("Fixed rate task async - " + System.currentTimeMillis() / 1000);
Thread.sleep(2000);
}
}

View File

@@ -0,0 +1,12 @@
package com.baeldung.scheduling;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
@Configuration
@EnableScheduling
@ComponentScan("com.baeldung.scheduling")
public class SpringSchedulingFixedRateConfig {
}

View File

@@ -0,0 +1,40 @@
package org.baeldung.async;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Component;
import java.util.concurrent.Future;
@Component
public class AsyncComponent {
@Async
public void asyncMethodWithVoidReturnType() {
System.out.println("Execute method asynchronously. " + Thread.currentThread().getName());
}
@Async
public Future<String> asyncMethodWithReturnType() {
System.out.println("Execute method asynchronously " + Thread.currentThread().getName());
try {
Thread.sleep(5000);
return new AsyncResult<>("hello world !!!!");
} catch (final InterruptedException e) {
}
return null;
}
@Async("threadPoolTaskExecutor")
public void asyncMethodWithConfiguredExecutor() {
System.out.println("Execute method asynchronously with configured executor" + Thread.currentThread().getName());
}
@Async
public void asyncMethodWithExceptions() throws Exception {
throw new Exception("Throw message from asynchronous method. ");
}
}

View File

@@ -0,0 +1,18 @@
package org.baeldung.async;
import java.lang.reflect.Method;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
public class CustomAsyncExceptionHandler implements AsyncUncaughtExceptionHandler {
@Override
public void handleUncaughtException(final Throwable throwable, final Method method, final Object... obj) {
System.out.println("Exception message - " + throwable.getMessage());
System.out.println("Method name - " + method.getName());
for (final Object param : obj) {
System.out.println("Param - " + param);
}
}
}

View File

@@ -0,0 +1,34 @@
package org.baeldung.async.config;
import java.util.concurrent.Executor;
import org.baeldung.async.CustomAsyncExceptionHandler;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.SimpleAsyncTaskExecutor;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
@Configuration
@EnableAsync()
@ComponentScan("org.baeldung.async")
public class SpringAsyncConfig implements AsyncConfigurer {
@Bean(name = "threadPoolTaskExecutor")
public Executor threadPoolTaskExecutor() {
return new ThreadPoolTaskExecutor();
}
@Override
public Executor getAsyncExecutor() {
return new SimpleAsyncTaskExecutor();
}
@Override
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
return new CustomAsyncExceptionHandler();
}
}

View File

@@ -0,0 +1,52 @@
package org.baeldung.scheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component("scheduledAnnotationExample")
public class ScheduledAnnotationExample {
@Scheduled(fixedDelay = 1000)
public void scheduleFixedDelayTask() {
System.out.println("Fixed delay task - " + System.currentTimeMillis() / 1000);
}
@Scheduled(fixedDelayString = "${fixedDelay.in.milliseconds}")
public void scheduleFixedDelayTaskUsingExpression() {
System.out.println("Fixed delay task - " + System.currentTimeMillis() / 1000);
}
@Scheduled(fixedDelay = 1000, initialDelay = 2000)
public void scheduleFixedDelayWithInitialDelayTask() {
System.out.println("Fixed delay task with one second initial delay - " + System.currentTimeMillis() / 1000);
}
@Scheduled(fixedRate = 1000)
public void scheduleFixedRateTask() {
System.out.println("Fixed rate task - " + System.currentTimeMillis() / 1000);
}
@Scheduled(fixedRateString = "${fixedRate.in.milliseconds}")
public void scheduleFixedRateTaskUsingExpression() {
System.out.println("Fixed rate task - " + System.currentTimeMillis() / 1000);
}
@Scheduled(fixedDelay = 1000, initialDelay = 100)
public void scheduleFixedRateWithInitialDelayTask() {
System.out.println("Fixed delay task with one second initial delay - " + System.currentTimeMillis() / 1000);
}
/**
* Scheduled task is executed at 10:15 AM on the 15th day of every month
*/
@Scheduled(cron = "0 15 10 15 * ?")
public void scheduleTaskUsingCronExpression() {
System.out.println("schedule tasks using cron expressions - " + System.currentTimeMillis() / 1000);
}
@Scheduled(cron = "${cron.expression}")
public void scheduleTaskUsingExternalizedCronExpression() {
System.out.println("schedule tasks using externalized cron expressions - " + System.currentTimeMillis() / 1000);
}
}

View File

@@ -0,0 +1,16 @@
package org.baeldung.scheduling;
public class SchedulingWithXmlConfig {
public void scheduleFixedDelayTask() {
System.out.println("Fixed delay task - " + System.currentTimeMillis() / 1000);
}
public void scheduleFixedRateTask() {
System.out.println("Fixed rate task - " + System.currentTimeMillis() / 1000);
}
public void scheduleTaskUsingCronExpression() {
System.out.println("schedule tasks using cron expressions - " + System.currentTimeMillis() / 1000);
}
}

View File

@@ -0,0 +1,20 @@
package org.baeldung.scheduling;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.scheduling.annotation.EnableScheduling;
@Configuration
@EnableScheduling
@ComponentScan("org.baeldung.scheduling")
@PropertySource("classpath:springScheduled.properties")
public class SpringSchedulingConfig {
@Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
}

View File

@@ -0,0 +1,34 @@
package org.baeldung.springretry;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.retry.annotation.EnableRetry;
import org.springframework.retry.backoff.FixedBackOffPolicy;
import org.springframework.retry.policy.SimpleRetryPolicy;
import org.springframework.retry.support.RetryTemplate;
@Configuration
@ComponentScan(basePackages = "org.baeldung.springretry")
@EnableRetry
// Uncomment this two lines if we need XML configuration
// @EnableAspectJAutoProxy
// @ImportResource("classpath:/retryadvice.xml")
public class AppConfig {
@Bean
public RetryTemplate retryTemplate() {
RetryTemplate retryTemplate = new RetryTemplate();
FixedBackOffPolicy fixedBackOffPolicy = new FixedBackOffPolicy();
fixedBackOffPolicy.setBackOffPeriod(2000l);
retryTemplate.setBackOffPolicy(fixedBackOffPolicy);
SimpleRetryPolicy retryPolicy = new SimpleRetryPolicy();
retryPolicy.setMaxAttempts(2);
retryTemplate.setRetryPolicy(retryPolicy);
retryTemplate.registerListener(new DefaultListenerSupport());
return retryTemplate;
}
}

View File

@@ -0,0 +1,31 @@
package org.baeldung.springretry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.retry.RetryCallback;
import org.springframework.retry.RetryContext;
import org.springframework.retry.listener.RetryListenerSupport;
public class DefaultListenerSupport extends RetryListenerSupport {
private static final Logger logger = LoggerFactory.getLogger(DefaultListenerSupport.class);
@Override
public <T, E extends Throwable> void close(RetryContext context, RetryCallback<T, E> callback, Throwable throwable) {
logger.info("onClose");
super.close(context, callback, throwable);
}
@Override
public <T, E extends Throwable> void onError(RetryContext context, RetryCallback<T, E> callback, Throwable throwable) {
logger.info("onError");
super.onError(context, callback, throwable);
}
@Override
public <T, E extends Throwable> boolean open(RetryContext context, RetryCallback<T, E> callback) {
logger.info("onOpen");
return super.open(context, callback);
}
}

View File

@@ -0,0 +1,21 @@
package org.baeldung.springretry;
import java.sql.SQLException;
import org.springframework.retry.annotation.Backoff;
import org.springframework.retry.annotation.Recover;
import org.springframework.retry.annotation.Retryable;
public interface MyService {
@Retryable
void retryService();
@Retryable(value = { SQLException.class }, maxAttempts = 2, backoff = @Backoff(delay = 5000))
void retryServiceWithRecovery(String sql) throws SQLException;
@Recover
void recover(SQLException e, String sql);
void templateRetryService();
}

View File

@@ -0,0 +1,39 @@
package org.baeldung.springretry;
import java.sql.SQLException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
@Service
public class MyServiceImpl implements MyService {
private static final Logger logger = LoggerFactory.getLogger(MyServiceImpl.class);
@Override
public void retryService() {
logger.info("throw RuntimeException in method retryService()");
throw new RuntimeException();
}
@Override
public void retryServiceWithRecovery(String sql) throws SQLException {
if (StringUtils.isEmpty(sql)) {
logger.info("throw SQLException in method retryServiceWithRecovery()");
throw new SQLException();
}
}
@Override
public void recover(SQLException e, String sql) {
logger.info("In recover method");
}
@Override
public void templateRetryService() {
logger.info("throw RuntimeException in method templateRetryService()");
throw new RuntimeException();
}
}

View File

@@ -0,0 +1,41 @@
package org.baeldung.taskscheduler;
import java.util.concurrent.TimeUnit;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.scheduling.support.PeriodicTrigger;
@Configuration
@ComponentScan(basePackages = "org.baeldung.taskscheduler", basePackageClasses = { ThreadPoolTaskSchedulerExamples.class })
public class ThreadPoolTaskSchedulerConfig {
@Bean
public ThreadPoolTaskScheduler threadPoolTaskScheduler() {
ThreadPoolTaskScheduler threadPoolTaskScheduler = new ThreadPoolTaskScheduler();
threadPoolTaskScheduler.setPoolSize(5);
threadPoolTaskScheduler.setThreadNamePrefix("ThreadPoolTaskScheduler");
return threadPoolTaskScheduler;
}
@Bean
public CronTrigger cronTrigger() {
return new CronTrigger("10 * * * * ?");
}
@Bean
public PeriodicTrigger periodicTrigger() {
return new PeriodicTrigger(2000, TimeUnit.MICROSECONDS);
}
@Bean
public PeriodicTrigger periodicFixedDelayTrigger() {
PeriodicTrigger periodicTrigger = new PeriodicTrigger(2000, TimeUnit.MICROSECONDS);
periodicTrigger.setFixedRate(true);
periodicTrigger.setInitialDelay(1000);
return periodicTrigger;
}
}

View File

@@ -0,0 +1,48 @@
package org.baeldung.taskscheduler;
import java.util.Date;
import javax.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.scheduling.support.PeriodicTrigger;
import org.springframework.stereotype.Component;
@Component
public class ThreadPoolTaskSchedulerExamples {
@Autowired
private ThreadPoolTaskScheduler taskScheduler;
@Autowired
private CronTrigger cronTrigger;
@Autowired
private PeriodicTrigger periodicTrigger;
@PostConstruct
public void scheduleRunnableWithCronTrigger() {
taskScheduler.schedule(new RunnableTask("Current Date"), new Date());
taskScheduler.scheduleWithFixedDelay(new RunnableTask("Fixed 1 second Delay"), 1000);
taskScheduler.scheduleWithFixedDelay(new RunnableTask("Current Date Fixed 1 second Delay"), new Date(), 1000);
taskScheduler.scheduleAtFixedRate(new RunnableTask("Fixed Rate of 2 seconds"), new Date(), 2000);
taskScheduler.scheduleAtFixedRate(new RunnableTask("Fixed Rate of 2 seconds"), 2000);
taskScheduler.schedule(new RunnableTask("Cron Trigger"), cronTrigger);
taskScheduler.schedule(new RunnableTask("Periodic Trigger"), periodicTrigger);
}
class RunnableTask implements Runnable {
private String message;
public RunnableTask(String message) {
this.message = message;
}
@Override
public void run() {
System.out.println("Runnable Task with " + message + " on thread " + Thread.currentThread().getName());
}
}
}

View File

@@ -0,0 +1,50 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<aop:config>
<aop:pointcut id="transactional"
expression="execution(* org.baeldung.springretry..*MyService.defaultXmlRetryService(..))" />
<aop:advisor pointcut-ref="transactional" advice-ref="taskRetryAdvice" order="-1" />
</aop:config>
<bean id="taskRetryAdvice" class="org.springframework.retry.interceptor.RetryOperationsInterceptor">
<property name="RetryOperations" ref="taskBatchRetryTemplate" />
</bean>
<bean id="taskBatchRetryTemplate" class="org.springframework.retry.support.RetryTemplate">
<property name="retryPolicy" ref="taskBatchRetryPolicy" />
<property name="backOffPolicy" ref="ExponentialBackOffPolicy" />
</bean>
<bean id="taskBatchRetryPolicy" class="org.springframework.retry.policy.SimpleRetryPolicy">
<constructor-arg index="0" value="2" />
<constructor-arg index="1">
<map>
<entry key="java.lang.RuntimeException" value="true" />
</map>
</constructor-arg>
</bean>
<bean id="ExponentialBackOffPolicy" class="org.springframework.retry.backoff.ExponentialBackOffPolicy">
<property name="initialInterval" value="300">
<description>
Initial sleep interval value, default 300 ms
</description>
</property>
<property name="maxInterval" value="30000">
<description>
The maximum value of the backoff period in milliseconds.
</description>
</property>
<property name="multiplier" value="2.0">
<description>
The value to increment the exp seed with for each retry attempt.
</description>
</property>
</bean>
</beans>

View File

@@ -0,0 +1,14 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:task="http://www.springframework.org/schema/task"
xsi:schemaLocation="http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.2.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd"
>
<task:annotation-driven executor="myExecutor"/>
<task:executor id="myExecutor" pool-size="5"/>
<bean id="asyncAnnotationExample" class="org.baeldung.async.AsyncComponent"/>
</beans>

View File

@@ -0,0 +1,25 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:task="http://www.springframework.org/schema/task"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd"
>
<context:property-placeholder location="classpath:springScheduled.properties"/>
<!-- Configure the scheduler -->
<task:scheduler id="myScheduler" pool-size="10"/>
<bean id="myscheduler" class="org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler"/>
<!-- Configure the fixedDealy, fixedRate or cron based schduled tasks -->
<bean id="schedulingWithXmlConfig" class="org.baeldung.scheduling.SchedulingWithXmlConfig"/>
<task:scheduled-tasks scheduler="myScheduler">
<task:scheduled ref="schedulingWithXmlConfig" method="scheduleFixedDelayTask" fixed-delay="${fixedDelay.in.milliseconds}" initial-delay="1000"/>
<task:scheduled ref="schedulingWithXmlConfig" method="scheduleFixedRateTask" fixed-rate="${fixedRate.in.milliseconds}"/>
<task:scheduled ref="schedulingWithXmlConfig" method="scheduleTaskUsingCronExpression" cron="${cron.expression}"/>
</task:scheduled-tasks>
</beans>

View File

@@ -0,0 +1,3 @@
cron.expression=0 15 10 15 * ?
fixedRate.in.milliseconds=1000
fixedDelay.in.milliseconds=1000

View File

@@ -0,0 +1,17 @@
package com.baeldung.scheduling;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { SpringSchedulingFixedRateConfig.class }, loader = AnnotationConfigContextLoader.class)
public class ScheduledFixedRateExampleIntegrationTest {
@Test
public void testScheduledFixedRateAnnotation() throws InterruptedException {
Thread.sleep(5000);
}
}

View File

@@ -0,0 +1,59 @@
package org.baeldung.async;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import org.baeldung.async.config.SpringAsyncConfig;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { SpringAsyncConfig.class }, loader = AnnotationConfigContextLoader.class)
public class AsyncAnnotationExampleIntegrationTest {
@Autowired
private AsyncComponent asyncAnnotationExample;
// tests
@Test
public void testAsyncAnnotationForMethodsWithVoidReturnType() {
System.out.println("Start - invoking an asynchronous method. " + Thread.currentThread().getName());
asyncAnnotationExample.asyncMethodWithVoidReturnType();
System.out.println("End - invoking an asynchronous method. ");
}
@Test
public void testAsyncAnnotationForMethodsWithReturnType() throws InterruptedException, ExecutionException {
System.out.println("Start - invoking an asynchronous method. " + Thread.currentThread().getName());
final Future<String> future = asyncAnnotationExample.asyncMethodWithReturnType();
while (true) {
if (future.isDone()) {
System.out.println("Result from asynchronous process - " + future.get());
break;
}
System.out.println("Continue doing something else. ");
Thread.sleep(1000);
}
}
@Test
public void testAsyncAnnotationForMethodsWithConfiguredExecutor() {
System.out.println("Start - invoking an asynchronous method. ");
asyncAnnotationExample.asyncMethodWithConfiguredExecutor();
System.out.println("End - invoking an asynchronous method. ");
}
@Test
public void testAsyncAnnotationForMethodsWithException() throws Exception {
System.out.println("Start - invoking an asynchronous method. ");
asyncAnnotationExample.asyncMethodWithExceptions();
System.out.println("End - invoking an asynchronous method. ");
}
}

View File

@@ -0,0 +1,26 @@
package org.baeldung.async;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:springAsync-config.xml")
public class AsyncWithXMLIntegrationTest {
@Autowired
private AsyncComponent asyncAnnotationExample;
// tests
@Test
public void testAsyncAnnotationForMethodsWithVoidReturnType() throws InterruptedException {
System.out.println("Start - invoking an asynchronous method. " + Thread.currentThread().getName());
asyncAnnotationExample.asyncMethodWithVoidReturnType();
Thread.sleep(2000);
System.out.println("End - invoking an asynchronous method. ");
}
}

View File

@@ -0,0 +1,17 @@
package org.baeldung.scheduling;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { SpringSchedulingConfig.class }, loader = AnnotationConfigContextLoader.class)
public class ScheduledAnnotationExampleIntegrationTest {
@Test
public void testScheduledAnnotation() throws InterruptedException {
Thread.sleep(5000);
}
}

View File

@@ -0,0 +1,16 @@
package org.baeldung.scheduling;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:springScheduled-config.xml")
public class SchedulingWithXmlConfigIntegrationTest {
@Test
public void testXmlBasedScheduling() throws InterruptedException {
Thread.sleep(5000);
}
}

View File

@@ -0,0 +1,40 @@
package org.baeldung.springretry;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.retry.support.RetryTemplate;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
import java.sql.SQLException;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = AppConfig.class, loader = AnnotationConfigContextLoader.class)
public class SpringRetryIntegrationTest {
@Autowired
private MyService myService;
@Autowired
private RetryTemplate retryTemplate;
@Test(expected = RuntimeException.class)
public void givenRetryService_whenCallWithException_thenRetry() {
myService.retryService();
}
@Test
public void givenRetryServiceWithRecovery_whenCallWithException_thenRetryRecover() throws SQLException {
myService.retryServiceWithRecovery(null);
}
@Test(expected = RuntimeException.class)
public void givenTemplateRetryService_whenCallWithException_thenRetry() {
retryTemplate.execute(arg0 -> {
myService.templateRetryService();
return null;
});
}
}

View File

@@ -0,0 +1,17 @@
package org.baeldung.taskscheduler;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { ThreadPoolTaskSchedulerConfig.class }, loader = AnnotationConfigContextLoader.class)
public class ThreadPoolTaskSchedulerIntegrationTest {
@Test
public void testThreadPoolTaskSchedulerAnnotation() throws InterruptedException {
Thread.sleep(2550);
}
}