资讯 小学 初中 高中 语言 会计职称 学历提升 法考 计算机考试 医护考试 建工考试 教育百科
栏目分类:
子分类:
返回
空麓网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
空麓网 > 计算机考试 > 软件开发 > 后端开发 > Java

Spring Scheduling 调度/定时任务

Java 更新时间: 发布时间: 计算机考试归档 最新发布

Spring Scheduling 调度/定时任务

前言
  • spring boot 2.2.13.RELEASE
Scheduling实例 创建 spring boot 项目

pom.xml



	4.0.0
	
		org.springframework.boot
		spring-boot-starter-parent
		2.2.13.RELEASE
		 
	
	
	test
	spring-task-test
	1.0
	
	
		1.8
		true
		true
	

	
		
			org.springframework.boot
			spring-boot-starter
		
	

	
		
			public
			aliyun nexus
			http://maven.aliyun.com/nexus/content/groups/public/
			
				true
			
		
	

	
		
			public
			aliyun nexus
			http://maven.aliyun.com/nexus/content/groups/public/
			
				true
			
			
				false
			
		
	



Application

package test;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.core.annotation.Order;
import org.springframework.scheduling.annotation.EnableScheduling;

@SpringBootApplication
@EnableScheduling
public class Application {
	private final Logger log = LoggerFactory.getLogger(this.getClass());
	
	public static void main(String[] args) {
		SpringApplication.run(Application.class, args);
	}
	
	@Order(999)
    @Bean
    public CommandLineRunner command999() {
    	return (args)->{
    		Thread.sleep(1000*4);
    		this.log.debug("the end");
    		System.exit(0);
    	};
    }

}

添加 Scheduling
package test;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
public class TestScheduling {
	private final Logger log = LoggerFactory.getLogger(this.getClass());
	
	@Scheduled(cron = "0/1 * * * * * ")
	public void scheduling01() {
		this.log.debug("scheduling01");
	}
	
	@Scheduled(cron = "0/3 * * * * * ")
	public void scheduling02() {
		this.log.debug("scheduling02");
	}
}

执行结果
  .   ____          _            __ _ _
 /\ / ___'_ __ _ _(_)_ __  __ _    
( ( )___ | '_ | '_| | '_ / _` |    
 \/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |___, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::       (v2.2.13.RELEASE)

2022-04-29 19:09:41.724  INFO 75380 --- [           main] test.Application                         : Starting Application on LAPTOP-F1O81IBU with PID 75380 (D:eclipse-workspacespring-task-testtargetclasses started by xxx in D:eclipse-workspacespring-task-test)
2022-04-29 19:09:41.730 DEBUG 75380 --- [           main] test.Application                         : Running with Spring Boot v2.2.13.RELEASE, Spring v5.2.12.RELEASE
2022-04-29 19:09:41.730  INFO 75380 --- [           main] test.Application                         : No active profile set, falling back to default profiles: default
2022-04-29 19:09:42.108  INFO 75380 --- [           main] test.Application                         : Started Application in 0.626 seconds (JVM running for 1.408)
2022-04-29 19:09:43.010 DEBUG 75380 --- [   scheduling-1] test.TestScheduling                      : scheduling01
2022-04-29 19:09:44.011 DEBUG 75380 --- [   scheduling-1] test.TestScheduling                      : scheduling01
2022-04-29 19:09:45.014 DEBUG 75380 --- [   scheduling-1] test.TestScheduling                      : scheduling02
2022-04-29 19:09:45.014 DEBUG 75380 --- [   scheduling-1] test.TestScheduling                      : scheduling01
2022-04-29 19:09:46.014 DEBUG 75380 --- [   scheduling-1] test.TestScheduling                      : scheduling01
2022-04-29 19:09:46.121 DEBUG 75380 --- [           main] ication$$EnhancerBySpringCGLIB$$5dacdb2f : the end
多线程

从上面的结果中可以看到,只有一个名为scheduling-1的线程供scheduling使用。
如需多个线程供scheduling使用,修改配置即可。

application.properties

# Maximum allowed number of threads.
spring.task.scheduling.pool.size=10
# Whether the executor should wait for scheduled tasks to complete on shutdown.
spring.task.scheduling.shutdown.await-termination = true
# Maximum time the executor should wait for remaining tasks to complete.
spring.task.scheduling.shutdown.await-termination-period = 10s
# Prefix to use for the names of newly created threads.
spring.task.scheduling.thread-name-prefix = scheduling-

再次执行上面的程序,结果如下:

  .   ____          _            __ _ _
 /\ / ___'_ __ _ _(_)_ __  __ _    
( ( )___ | '_ | '_| | '_ / _` |    
 \/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |___, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::       (v2.2.13.RELEASE)

2022-04-29 19:17:07.936  INFO 72368 --- [           main] test.Application                         : Starting Application on LAPTOP-F1O81IBU with PID 72368 (D:eclipse-workspacespring-task-testtargetclasses started by xxx in D:eclipse-workspacespring-task-test)
2022-04-29 19:17:07.938 DEBUG 72368 --- [           main] test.Application                         : Running with Spring Boot v2.2.13.RELEASE, Spring v5.2.12.RELEASE
2022-04-29 19:17:07.938  INFO 72368 --- [           main] test.Application                         : No active profile set, falling back to default profiles: default
2022-04-29 19:17:08.356  INFO 72368 --- [           main] test.Application                         : Started Application in 0.652 seconds (JVM running for 1.457)
2022-04-29 19:17:09.005 DEBUG 72368 --- [   scheduling-2] test.TestScheduling                      : scheduling02
2022-04-29 19:17:09.005 DEBUG 72368 --- [   scheduling-1] test.TestScheduling                      : scheduling01
2022-04-29 19:17:10.007 DEBUG 72368 --- [   scheduling-2] test.TestScheduling                      : scheduling01
2022-04-29 19:17:11.016 DEBUG 72368 --- [   scheduling-1] test.TestScheduling                      : scheduling01
2022-04-29 19:17:12.011 DEBUG 72368 --- [   scheduling-4] test.TestScheduling                      : scheduling02
2022-04-29 19:17:12.011 DEBUG 72368 --- [   scheduling-3] test.TestScheduling                      : scheduling01
2022-04-29 19:17:12.370 DEBUG 72368 --- [           main] lication$$EnhancerBySpringCGLIB$$7249eea : the end
自动配置 @EnableScheduling

@EnableScheduling启用 @Scheduled 、@Schedules 注解

TaskSchedulingAutoConfiguration

TaskSchedulingAutoConfiguration 负责配置 ThreadPoolTaskScheduler Bean:

@ConditionalOnClass(ThreadPoolTaskScheduler.class)
@Configuration(proxyBeanMethods = false)
@EnableConfigurationProperties(TaskSchedulingProperties.class)
@AutoConfigureAfter(TaskExecutionAutoConfiguration.class)
public class TaskSchedulingAutoConfiguration {

	@Bean
	@ConditionalOnBean(name = TaskManagementConfigUtils.SCHEDULED_ANNOTATION_PROCESSOR_BEAN_NAME)
	@ConditionalOnMissingBean({ SchedulingConfigurer.class, TaskScheduler.class, ScheduledExecutorService.class })
	public ThreadPoolTaskScheduler taskScheduler(TaskSchedulerBuilder builder) {
		return builder.build();
	}

	@Bean
	@ConditionalOnMissingBean
	public TaskSchedulerBuilder taskSchedulerBuilder(TaskSchedulingProperties properties,
			ObjectProvider taskSchedulerCustomizers) {
		TaskSchedulerBuilder builder = new TaskSchedulerBuilder();
		builder = builder.poolSize(properties.getPool().getSize());
		Shutdown shutdown = properties.getShutdown();
		builder = builder.awaitTermination(shutdown.isAwaitTermination());
		builder = builder.awaitTerminationPeriod(shutdown.getAwaitTerminationPeriod());
		builder = builder.threadNamePrefix(properties.getThreadNamePrefix());
		builder = builder.customizers(taskSchedulerCustomizers);
		return builder;
	}

}
官方文档

Task Execution and Scheduling
spring-boot-autoconfigure

转载请注明:文章转载自 http://www.konglu.com/
本文地址:http://www.konglu.com/it/845852.html
免责声明:

我们致力于保护作者版权,注重分享,被刊用文章【Spring Scheduling 调度/定时任务】因无法核实真实出处,未能及时与作者取得联系,或有版权异议的,请联系管理员,我们会立即处理,本文部分文字与图片资源来自于网络,转载此文是出于传递更多信息之目的,若有来源标注错误或侵犯了您的合法权益,请立即通知我们,情况属实,我们会第一时间予以删除,并同时向您表示歉意,谢谢!

我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2023 成都空麓科技有限公司

ICP备案号:蜀ICP备2023000828号-2