1、基于springboot的项目开启自动配置
- package com.plateno.booking.sync.vienna;
- import javax.annotation.PostConstruct;
- import javax.jms.ConnectionFactory;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.boot.SpringApplication;
- import org.springframework.boot.autoconfigure.SpringBootApplication;
- import org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration;
- import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
- import org.springframework.boot.autoconfigure.jms.DefaultJmsListenerContainerFactoryConfigurer;
- import org.springframework.context.annotation.Bean;
- import org.springframework.context.annotation.ImportResource;
- import org.springframework.data.redis.core.RedisTemplate;
- import org.springframework.jms.config.DefaultJmsListenerContainerFactory;
- import org.springframework.jms.config.JmsListenerContainerFactory;
- import org.springframework.jms.core.JmsTemplate;
- import org.springframework.jms.support.converter.MessageConverter;
- import org.springframework.scheduling.annotation.EnableAsync;
- import org.springframework.scheduling.annotation.EnableScheduling;
- import com.plateno.booking.sync.vienna.annotation.EnableMysql;
- import com.plateno.booking.sync.vienna.annotation.EnableRedis;
- import com.plateno.booking.sync.vienna.jms.messageconverter.PlatenoMessageConverter;
- import com.plateno.booking.sync.vienna.util.BookingRedisHelper;
- import com.plateno.booking.sync.vienna.util.SpringContextUtils;
- //@EnableMysql
- //@EnableRedis
- //开启自动配置
- @SpringBootApplication(exclude = {
- DataSourceAutoConfiguration.class,
- RedisAutoConfiguration.class
- }, scanBasePackageClasses = {
- BookingSyncVienna.class })
- public class BookingSyncVienna {
- public static void main(String[] args) {
- SpringApplication springApplication = new SpringApplication(BookingSyncVienna.class);
- springApplication.run(args);
- }
- @Autowired
- JmsTemplate jmsTemplate;
- @Bean
- MessageConverter messageConverter() {
- return new PlatenoMessageConverter();
- }
- @Bean
- SpringContextUtils springContextUtils() {
- return new SpringContextUtils();
- }
- @PostConstruct
- public void init() {
- this.jmsTemplate.setMessageConverter(messageConverter());
- }
- /**
- * 创建默认的listerFactory
- * see:JmsListenerAnnotationBeanPostProcessor->static final String DEFAULT_JMS_LISTENER_CONTAINER_FACTORY_BEAN_NAME = "jmsListenerContainerFactory";
- * @param connectionFactory
- * @param configurer
- * @return
- */
- @Bean(name="jmsListenerContainerFactory")
- public JmsListenerContainerFactory<?> jmsListenerContainerFactory(ConnectionFactory connectionFactory,
- DefaultJmsListenerContainerFactoryConfigurer configurer) {
- DefaultJmsListenerContainerFactory factory = new DefaultJmsListenerContainerFactory();
- factory.setMessageConverter(messageConverter());
- configurer.configure(factory, connectionFactory);
- return factory;
- }
- /* @Bean
- @Autowired
- public BookingRedisHelper redisHelper(RedisTemplate redisTemplate) {
- BookingRedisHelper bookingRedisHelper = new BookingRedisHelper();
- bookingRedisHelper.setRedisTemplate(redisTemplate);
- return bookingRedisHelper;
- }
- */
- /*
- * @Bean public DefaultJmsListenerContainerFactory
- * listenerContainerFactory() { DefaultJmsListenerContainerFactory factory =
- * new DefaultJmsListenerContainerFactory();
- * factory.setConnectionFactory(connectionFactory());
- * factory.setMessageConverter(objectConverter());
- * factory.setConcurrency("5"); return factory; }
- */
- /*
- * @Bean public ConnectionFactory connectionFactory(){
- * PooledConnectionFactory pooledConnectionFactory = new
- * PooledConnectionFactory(); ActiveMQConnectionFactory mqConnectionFactory
- * = new ActiveMQConnectionFactory();
- * mqConnectionFactory.setBrokerURL(brokerUrl);
- * mqConnectionFactory.setUseAsyncSend(true);
- * mqConnectionFactory.setOptimizeAcknowledgeTimeOut(3000);
- * pooledConnectionFactory.setConnectionFactory(mqConnectionFactory);
- * pooledConnectionFactory.setMaxConnections(20);
- * mqConnectionFactory.setTransactedIndividualAck(true); return
- * pooledConnectionFactory; }
- */
- }
2、创建作业类
- package com.plateno.booking.sync.vienna.test;
- import org.slf4j.Logger;
- import org.slf4j.LoggerFactory;
- import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
- import org.springframework.scheduling.annotation.Async;
- import org.springframework.scheduling.annotation.Scheduled;
- import org.springframework.stereotype.Component;
- import com.plateno.booking.sync.vienna.properties.CronProperties;
- @Component
- @ConditionalOnProperty(prefix = "", name = "test", havingValue = "true")
- public class TestJob {
- private static Logger logger = LoggerFactory.getLogger(TestJob.class);
- @Scheduled(cron="0/2 * * * * ?")
- @Async//异步执行,配合线程池实现并发
- public void test(){
- System.err.println("---------------------");
- System.err.println("a");
- logger.error(Thread.currentThread().getName());
- System.err.println("---------------------");
- try {
- Thread.sleep(20000);//执行睡眠,这样如果并发执行,那么上面的打印会2秒执行一次,而下面的ffff则会22秒打印一次
- System.out.println("ffff");
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- /*@Scheduled(cron="0/1 * * * * ?")
- public void test1(){
- System.err.println("---------------------");
- System.err.println("b");
- logger.error(Thread.currentThread().getName());
- System.err.println("---------------------");
- }*/
- }
3、定义线程池配置文件(@enableSchedulling@scheduled默认是基于单线程),多线程并发需要配置xml
- <?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/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
- http://www.springframework.org/schema/task
- http://www.springframework.org/schema/task/spring-task-4.2.xsd">
- <task:scheduler id="scheduler" pool-size="10" />
- <task:executor id="executor" keep-alive="7200" pool-size="100-200"
- queue-capacity="500" rejection-policy="CALLER_RUNS" />
- <task:annotation-driven executor="executor"
- scheduler="scheduler" />
- </beans>
同时,如果想使用注解开发
配置类加上@EnableAsync即可,本质上都是创建AsyncAnnotationBeanPostProcessor对象,另外如果要自定义excutor和exceptionHandller,可以参考@EnableAsync源码
注释:
- /**
- * Enables Spring's asynchronous method execution capability, similar to functionality
- * found in Spring's {@code <task:*>} XML namespace.
- *
- * <p>To be used on @{@link Configuration} classes as follows, where {@code MyAsyncBean}
- * is a user-defined type with one or more methods annotated with either Spring's
- * {@code @Async} annotation, the EJB 3.1 {@code @javax.ejb.Asynchronous} annotation,
- * or any custom annotation specified via the {@link #annotation} attribute.
- *
- * <pre class="code">
- * @Configuration
- * @EnableAsync
- * public class AppConfig {
- *
- * @Bean
- * public MyAsyncBean asyncBean() {
- * return new MyAsyncBean();
- * }
- * }</pre>
- *
- * <p>The {@link #mode} attribute controls how advice is applied; if the mode is
- * {@link AdviceMode#PROXY} (the default), then the other attributes control the behavior
- * of the proxying.
- *
- * <p>Note that if the {@linkplain #mode} is set to {@link AdviceMode#ASPECTJ}, then the
- * value of the {@link #proxyTargetClass} attribute will be ignored. Note also that in
- * this case the {@code spring-aspects} module JAR must be present on the classpath.
- *
- * <p>By default, Spring will be searching for an associated thread pool definition:
- * either a unique {@link org.springframework.core.task.TaskExecutor} bean in the context,
- * or an {@link java.util.concurrent.Executor} bean named "taskExecutor" otherwise. If
- * neither of the two is resolvable, a {@link org.springframework.core.task.SimpleAsyncTaskExecutor}
- * will be used to process async method invocations. Besides, annotated methods having a
- * {@code void} return type cannot transmit any exception back to the caller. By default,
- * such uncaught exceptions are only logged.
- *
- * <p>To customize all this, implement {@link AsyncConfigurer} and provide:
- * <ul>
- * <li>your own {@link java.util.concurrent.Executor Executor} through the
- * {@link AsyncConfigurer#getAsyncExecutor getAsyncExecutor()} method, and</li>
- * <li>your own {@link org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler
- * AsyncUncaughtExceptionHandler} through the {@link AsyncConfigurer#getAsyncUncaughtExceptionHandler
- * getAsyncUncaughtExceptionHandler()}
- * method.</li>
- * </ul>
- *
- * <pre class="code">
- * @Configuration
- * @EnableAsync
- * public class AppConfig implements AsyncConfigurer {
- *
- * @Bean
- * public MyAsyncBean asyncBean() {
- * return new MyAsyncBean();
- * }
- *
- * @Override
- * public Executor getAsyncExecutor() {
- * ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
- * executor.setCorePoolSize(7);
- * executor.setMaxPoolSize(42);
- * executor.setQueueCapacity(11);
- * executor.setThreadNamePrefix("MyExecutor-");
- * executor.initialize();
- * return executor;
- * }
- *
- * @Override
- * public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
- * return MyAsyncUncaughtExceptionHandler();
- * }
- * }</pre>
- *
- * <p>If only one item needs to be customized, {@code null} can be returned to
- * keep the default settings. Consider also extending from {@link AsyncConfigurerSupport}
- * when possible.
- *
- * <p>Note: In the above example the {@code ThreadPoolTaskExecutor} is not a fully managed
- * Spring bean. Add the {@code @Bean} annotation to the {@code getAsyncExecutor()} method
- * if you want a fully managed bean. In such circumstances it is no longer necessary to
- * manually call the {@code executor.initialize()} method as this will be invoked
- * automatically when the bean is initialized.
- *
- * <p>For reference, the example above can be compared to the following Spring XML
- * configuration:
- *
- * <pre class="code">
- * {@code
- * <beans>
- *
- * <task:annotation-driven executor="myExecutor" exception-handler="exceptionHandler"/>
- *
- * <task:executor id="myExecutor" pool-size="7-42" queue-capacity="11"/>
- *
- * <bean id="asyncBean" class="com.foo.MyAsyncBean"/>
- *
- * <bean id="exceptionHandler" class="com.foo.MyAsyncUncaughtExceptionHandler"/>
- *
- * </beans>
- * }</pre>
参考:http://docs.spring.io/spring/docs/current/spring-framework-reference/html/scheduling.html
执行结果:
图片无法显示:睡眠之前的2秒打印一次,睡眠之后的22秒打印一次
相关推荐
`@Scheduled`注解是Spring Framework中用于创建定时任务的重要工具,它允许开发者在不重启应用的情况下,实现定时任务的动态配置,特别是修改cron表达式来调整执行周期。 在Spring中,定时任务主要通过`@Scheduled`...
同时,`@Scheduled`注解还支持更复杂的配置,如任务队列、线程池等,以提高任务执行的效率和并发能力。 总结一下,Spring Boot的`@Scheduled`注解是实现定时任务的关键,配合cron表达式,我们可以轻松地创建按时间...
### 使用Spring `@Scheduled` 注解执行定时任务 在现代软件开发中,特别是企业级应用领域,定时任务处理是一项常见的需求。例如,自动备份数据库、定时发送报告邮件、定期清理缓存等。Spring 框架自3.0版本起引入了...
总结,`@Scheduled`任务调度是Spring Boot中实现定时任务的关键,它可以配合多线程和`@Async`异步任务提升程序的并发性能。通过自定义线程池和配置`TaskExecutor`,我们可以更好地控制任务的执行方式,从而优化应用...
在Spring框架中,`@Scheduled`注解用于创建定时任务,它使得开发者能够方便地定义周期性的任务执行。然而,`@Scheduled`默认是单线程执行的,这意味着所有使用该注解的任务会按照预设的时间间隔顺序执行,一旦某个...
- `@Scheduled`是Spring-task的核心注解,用于标记一个方法为定时任务。例如: ```java @Component public class ScheduledTasks { @Scheduled(fixedRate = 5000) public void reportCurrentTime() { System....
此外,如果你需要更复杂的任务调度,比如任务依赖、并发控制等,可以考虑使用Spring Integration或Quartz等更强大的调度库,它们提供了更多的功能和控制。 总的来说,Spring Boot的`@Scheduled`注解为开发者提供了...
Spring定时器还支持动态修改任务执行计划,例如通过`ThreadPoolTaskScheduler`或`ConcurrentTaskScheduler`来调整线程池大小,控制并发执行的任务数量。此外,我们还可以通过`@Scheduled`注解的`initialDelay`属性来...
虽然`@Scheduled`已经足够强大,但若需要更复杂的时间调度或者并发控制,可以考虑集成Quartz Scheduler。Spring提供了`SpringBeanJobFactory`和`org.springframework.scheduling.quartz.SchedulerFactoryBean`来方便...
`@Scheduled` 是 Spring 提供的一个注解,用于声明周期性的任务。下面我们将详细探讨这些知识点。 1. **Spring Scheduler 概述** Spring Scheduler 提供了一种在 Spring 应用程序中执行定时任务的机制。它允许...
通过`@Scheduled`注解,你可以将方法标记为定时任务,Spring会自动处理任务的调度。 2. **配置**: 在Spring配置中,你需要创建一个`TaskScheduler`或`ThreadPoolTaskScheduler`实例。例如,在XML配置中: ```...
在开发Java Web应用程序时,定时任务的实现是一个常见的需求,Spring Boot为我们提供了两种主要的解决方案:Spring Boot的`@Scheduled`注解和Quartz Scheduler。本文将深入探讨这两种选择的适用场景、优缺点,以及...
总结起来,Spring MVC通过`@Scheduled`注解结合`TaskScheduler`,使得在Java应用中设置定时任务变得简单且易于管理。开发者可以根据需求选择合适的执行策略,如固定间隔或cron表达式,以满足各种定时场景。同时,...
Spring为实现定时任务提供了`@Scheduled`注解,可以将其添加到方法上,指定任务的执行时间。例如: ```java @Component public class MyScheduledTask { @Scheduled(fixedRate = 5000) // 每5秒执行一次 ...
Spring定时任务基于`@Scheduled`注解和`TaskScheduler`接口实现。`@Scheduled`用于标注需要定时执行的方法,而`TaskScheduler`则提供了更灵活的定时任务调度方式。 2. **启用定时任务** 要使用Spring定时任务,...
import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; @Component public class MyTask { @Scheduled(cron = "0 0/5 * * * ?") public void run() {...
Spring Task还支持异步执行任务,通过`@Async`注解,可以将任务方法标记为异步执行,提高系统并发性能。 ```java @Service @EnableAsync public class AsyncService { @Async public void longRunningTask() { ...
1. **Spring的`@Scheduled`注解**:这是Spring Framework提供的一个用于创建定时任务的注解。你可以直接在方法上添加`@Scheduled`,并设置定时策略,如固定延迟、固定间隔或者cron表达式。例如: ```java @...
首先,Spring提供了两种主要的定时任务解决方案:一是Spring内置的`TaskScheduler`接口,二是基于Quartz库的`@Scheduled`注解。`TaskScheduler`提供了一种异步执行任务的方式,适合于简单的定时任务需求。而`@...
1. **ThreadPoolTaskExecutor**:这是一个线程池任务执行器,它允许我们异步执行任务,适用于大量并发的任务执行。 2. **ScheduledTaskRegistrar**:这是一个注册器,用来注册定时任务。 3. **...