欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

SpringBoot創(chuàng)建定時(shí)任務(wù)的示例詳解

 更新時(shí)間:2024年04月23日 09:57:34   作者:青燈文案1  
在Spring Boot中創(chuàng)建定時(shí)任務(wù),通常使用@Scheduled注解,這是Spring框架提供的一個(gè)功能,允許你按照固定的頻率(如每天、每小時(shí)、每分鐘等)執(zhí)行某個(gè)方法,本文給大家介紹了SpringBoot創(chuàng)建定時(shí)任務(wù)的示例,需要的朋友可以參考下

網(wǎng)上有很多 icon表達(dá)式生成器 ,可以直接搜索 定時(shí)任務(wù)icon表達(dá)式生成器 ,這里就不放鏈接了。

1、在入口類開(kāi)啟定時(shí)任務(wù)支持

在 SpringBoot 應(yīng)用的啟動(dòng)類上,添加 @EnableScheduling 注解來(lái)開(kāi)啟定時(shí)任務(wù)的支持。

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;

@SpringBootApplication
@EnableScheduling
public class Application {

	public static void main(String[] args) {
		SpringApplication.run(Application.class, args);
	}
}

2、創(chuàng)建定時(shí)任務(wù)

創(chuàng)建一個(gè)包含定時(shí)任務(wù)方法的類,并在該方法上使用@Scheduled注解來(lái)指定任務(wù)的執(zhí)行頻率。

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
public class ScheduledTasks {

	// 每5秒執(zhí)行一次
	@Scheduled(fixedRate = 5000)
	public void doTaskEveryFiveSeconds() {
		System.out.println("任務(wù)每5秒執(zhí)行一次:" + new Date());
	}

	// 每天的特定時(shí)間執(zhí)行一次
	@Scheduled(cron = "0 0 12 * * ?") // 每天中午12點(diǎn)執(zhí)行
	public void doTaskEveryDayAtNoon() {
		System.out.println("任務(wù)每天中午12點(diǎn)執(zhí)行一次:" + new Date());
	}
}
  • fixedRate 屬性用于指定任務(wù)執(zhí)行的固定頻率(以毫秒為單位)。
  • cron 屬性則允許你使用CRON表達(dá)式來(lái)指定任務(wù)的執(zhí)行時(shí)間。

這兩個(gè)屬性在實(shí)際的項(xiàng)目開(kāi)發(fā)中都會(huì)做到配置文件中,便于修改。

3、配置定時(shí)任務(wù)線程池(可選)

默認(rèn)情況下,Spring Boot使用單線程來(lái)執(zhí)行所有的定時(shí)任務(wù)。如果需要并發(fā)執(zhí)行多個(gè)定時(shí)任務(wù),或者某個(gè)任務(wù)執(zhí)行時(shí)間較長(zhǎng)不希望阻塞其他任務(wù),可以自定義定時(shí)任務(wù)的線程池。

在 application.properties 中設(shè)置相關(guān)配置

spring.task.scheduling.pool.size=5 # 線程池大小,可以用 ${} 配置
spring.task.scheduling.thread-name-prefix=task-scheduler- # 線程名前綴

也可以在配置類中自定義 TaskScheduler Bean

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;

@Configuration
public class SchedulerConfig {

	@Bean
	public ThreadPoolTaskScheduler threadPoolTaskScheduler() {
		ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
		scheduler.setPoolSize(5);
		scheduler.setThreadNamePrefix("task-scheduler-");
		return scheduler;
	}
}

啟動(dòng)SpringBoot應(yīng)用,定時(shí)任務(wù)就會(huì)按照指定的頻率執(zhí)行。

請(qǐng)注意,@Scheduled注解的方法不應(yīng)該有任何參數(shù),并且返回類型應(yīng)該是void。此外,@Scheduled注解的方法可以定義在配置類中,但最好將其定義在一個(gè)獨(dú)立的Bean中,以便于測(cè)試和管理。

以上就是SpringBoot創(chuàng)建定時(shí)任務(wù)的示例詳解的詳細(xì)內(nèi)容,更多關(guān)于SpringBoot創(chuàng)建定時(shí)任務(wù)的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

最新評(píng)論