IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> Java知识库 -> Spring Scheduling 调度/定时任务 -> 正文阅读

[Java知识库]Spring Scheduling 调度/定时任务

前言

  • spring boot 2.2.13.RELEASE

Scheduling实例

创建 spring boot 项目

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.2.13.RELEASE</version>
		<relativePath /> <!-- lookup parent from repository -->
	</parent>
	
	<groupId>test</groupId>
	<artifactId>spring-task-test</artifactId>
	<version>1.0</version>
	
	<properties>
		<java.version>1.8</java.version>
		<maven.install.skip>true</maven.install.skip>
		<maven.deploy.skip>true</maven.deploy.skip>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter</artifactId>
		</dependency>
	</dependencies>

	<repositories>
		<repository>
			<id>public</id>
			<name>aliyun nexus</name>
			<url>http://maven.aliyun.com/nexus/content/groups/public/</url>
			<releases>
				<enabled>true</enabled>
			</releases>
		</repository>
	</repositories>

	<pluginRepositories>
		<pluginRepository>
			<id>public</id>
			<name>aliyun nexus</name>
			<url>http://maven.aliyun.com/nexus/content/groups/public/</url>
			<releases>
				<enabled>true</enabled>
			</releases>
			<snapshots>
				<enabled>false</enabled>
			</snapshots>
		</pluginRepository>
	</pluginRepositories>

</project>

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-workspace\spring-task-test\target\classes started by xxx in D:\eclipse-workspace\spring-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-workspace\spring-task-test\target\classes started by xxx in D:\eclipse-workspace\spring-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:

/**
 * {@link EnableAutoConfiguration Auto-configuration} for {@link TaskScheduler}.
 *
 * @author Stephane Nicoll
 * @since 2.1.0
 */
@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<TaskSchedulerCustomizer> 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

  Java知识库 最新文章
计算距离春节还有多长时间
系统开发系列 之WebService(spring框架+ma
springBoot+Cache(自定义有效时间配置)
SpringBoot整合mybatis实现增删改查、分页查
spring教程
SpringBoot+Vue实现美食交流网站的设计与实
虚拟机内存结构以及虚拟机中销毁和新建对象
SpringMVC---原理
小李同学: Java如何按多个字段分组
打印票据--java
上一篇文章      下一篇文章      查看所有文章
加:2022-05-01 15:33:33  更:2022-05-01 15:34:30 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年11日历 -2024/11/24 2:19:16-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码