最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Java Spring分別實現(xiàn)定時任務方法

 更新時間:2022年07月12日 11:56:52   作者:少年.  
這篇文章主要為大家詳細介紹了Java與Spring設置動態(tài)定時任務的方法,定時任務的應用場景十分廣泛,如定時清理文件、定時生成報表、定時數(shù)據(jù)同步備份等

java實現(xiàn)定時任務

Jdk自帶的庫中,有兩種方式可以實現(xiàn)定時任務,一種是Timer,另一種是ScheduledThreadPoolExecutor。

Timer+TimerTask

創(chuàng)建一個Timer就創(chuàng)建了一個線程,可以用來調度TimerTask任務

Timer有四個構造方法,可以指定Timer線程的名字以及是否設置為為守護線程。默認名字Timer-編號,默認不是守護線程。

主要有三個比較重要的方法:

cancel():終止任務調度,取消當前調度的所有任務,正在運行的任務不受影響

purge():從任務隊列中移除所有已經取消的任務

schedule:開始調度任務,提供了幾個重載方法:

schedule(TimerTask task, long delay)延時執(zhí)行,表示delay毫秒后執(zhí)行一次task任務

schedule(TimerTask task, Date time)`指定時間執(zhí)行,到`time`時間的時候執(zhí)行一次`task
schedule(TimerTask task, long delay, long period)`延時周期執(zhí)行,經過`delay`毫秒后每`period`毫秒執(zhí)行一次`task
schedule(TimerTask task, Date firstTime, long period)`指定時間后周期執(zhí)行,到達指定時間`firstTime`后每`period`毫秒執(zhí)行一次`task

示例

public class TimerTest {
    public static void main(String[] args) {
        Timer timer = new Timer("aa");
        Task task = new Task();
        timer.schedule(task,new Date(),1000);
    }
}
class Task extends TimerTask{
    @Override
    public void run() {
        System.out.println(new Date());
    }
}

輸出:
Thu Jul 07 14:50:02 CST 2022
Thu Jul 07 14:50:03 CST 2022
Thu Jul 07 14:50:04 CST 2022
Thu Jul 07 14:50:05 CST 2022
…………

弊端

Timer是單線程的,并且不會拋出異常,一旦定時任務拋出異常,將會導致整個線程停止,即定時任務停止。

ScheduledThreadPoolExecutor

因為Timer的缺陷,所以不建議使用Timer,建議使用ScheduledThreadPoolExecutor

ScheduledThreadPoolExecutorTimer的替代者,于JDK1.5引入,繼承了ThreadPoolExecutor,是基于線程池設計的定時任務類。

主要的調度方法:

schedule只執(zhí)行一次調度,(任務,延遲時間,延遲時間單位)

scheduleAtFixedRate按固定的頻率調度,如果執(zhí)行時間過長,下次調度會延遲,(任務,第一次執(zhí)行的延遲時間,周期,時間單位)

scheduleWithFixedDelay延遲調度,一次任務執(zhí)行完后加上延遲時間執(zhí)行下一次任務,(任務,第一次執(zhí)行的延遲時間,間隔時間,時間單位)

示例

public class TimerTest {
    public static void main(String[] args) throws Exception{
        ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(10);
        scheduledExecutorService.scheduleAtFixedRate(
                () -> System.out.println(new Date()),
                1,3, TimeUnit.SECONDS);
    }
}

Spring定時任務

Spring定時任務主要靠@Scheduled注解實現(xiàn),corn,fixedDelay,fixedDelayString,fixedRate,fixedRateString五個參數(shù)必須指定其一,傳兩個或三個都會拋出異常

@Target({ElementType.METHOD, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Repeatable(Schedules.class)
public @interface Scheduled {
	String CRON_DISABLED = ScheduledTaskRegistrar.CRON_DISABLED;
    // cron表達式
	String cron() default "";
    // 時區(qū)
	String zone() default "";
    // 從上一次調用結束到下一次調用之間的固定時間
	long fixedDelay() default -1;
    // 和fixedDelay意思相同,只是使用字符傳格式,支持占位符。例如:fixedDelayString = "${time.fixedDelay}"
	String fixedDelayString() default "";
    // 兩次調用之間固定的毫秒數(shù)(不需要等待上次任務完成)
	long fixedRate() default -1;
    // 同上,支持占位符
	String fixedRateString() default "";
    // 第一次執(zhí)行任務前延遲的毫秒數(shù)
	long initialDelay() default -1;
    // 同上,支持占位符
	String initialDelayString() default "";
}

示例

@Component
@EnableScheduling
public class ScheduledTask {
    @Scheduled(fixedDelay = 1000)
    public void task(){
        System.out.println("aaa");
    }
}

原理

項目啟動ScheduledAnnotationBeanPostProcessorpostProcessAfterInitialization()方法掃描帶有@Scheduled注解的方法:

	@Override
	public Object postProcessAfterInitialization(Object bean, String beanName) {
		if (bean instanceof AopInfrastructureBean || bean instanceof TaskScheduler ||
				bean instanceof ScheduledExecutorService) {
			// Ignore AOP infrastructure such as scoped proxies.
			return bean;
		}
		Class<?> targetClass = AopProxyUtils.ultimateTargetClass(bean);
		if (!this.nonAnnotatedClasses.contains(targetClass) &&
				AnnotationUtils.isCandidateClass(targetClass, Arrays.asList(Scheduled.class, Schedules.class))) {
			Map<Method, Set<Scheduled>> annotatedMethods = MethodIntrospector.selectMethods(targetClass,
					(MethodIntrospector.MetadataLookup<Set<Scheduled>>) method -> {
						Set<Scheduled> scheduledMethods = AnnotatedElementUtils.getMergedRepeatableAnnotations(
								method, Scheduled.class, Schedules.class);
						return (!scheduledMethods.isEmpty() ? scheduledMethods : null);
					});
			if (annotatedMethods.isEmpty()) {
				this.nonAnnotatedClasses.add(targetClass);
				if (logger.isTraceEnabled()) {
					logger.trace("No @Scheduled annotations found on bean class: " + targetClass);
				}
			}
			else {
				// Non-empty set of methods
				annotatedMethods.forEach((method, scheduledMethods) ->
                        // 調用processScheduled方法將定時任務的方法存放到任務隊列中
						scheduledMethods.forEach(scheduled -> processScheduled(scheduled, method, bean)));
				if (logger.isTraceEnabled()) {
					logger.trace(annotatedMethods.size() + " @Scheduled methods processed on bean '" + beanName +
							"': " + annotatedMethods);
				}
			}
		}
		return bean;
	}
	protected void processScheduled(Scheduled scheduled, Method method, Object bean) {
		try {
            // 創(chuàng)建任務線程
			Runnable runnable = createRunnable(bean, method);
            // 解析到定時任務方式的標記,解析到正確的參數(shù)后會設置為TRUE,如果在解析到了其他的參數(shù)就會拋出異常
			boolean processedSchedule = false;
			String errorMessage =
					"Exactly one of the 'cron', 'fixedDelay(String)', or 'fixedRate(String)' attributes is required";
			Set<ScheduledTask> tasks = new LinkedHashSet<>(4);
			// Determine initial delay 解析第一次的延遲(解析initialDelay參數(shù))
			long initialDelay = scheduled.initialDelay();
			String initialDelayString = scheduled.initialDelayString();
			if (StringUtils.hasText(initialDelayString)) {
                // initialDelay不能小于0
				Assert.isTrue(initialDelay < 0, "Specify 'initialDelay' or 'initialDelayString', not both");
				if (this.embeddedValueResolver != null) {
					initialDelayString = this.embeddedValueResolver.resolveStringValue(initialDelayString);
				}
				if (StringUtils.hasLength(initialDelayString)) {
					try {
						initialDelay = parseDelayAsLong(initialDelayString);
					}
					catch (RuntimeException ex) {
						throw new IllegalArgumentException(
								"Invalid initialDelayString value \"" + initialDelayString + "\" - cannot parse into long");
					}
				}
			}
			// Check cron expression 解析cron表達式
			String cron = scheduled.cron();
			if (StringUtils.hasText(cron)) {
                // 解析時區(qū)
				String zone = scheduled.zone();
				if (this.embeddedValueResolver != null) {
					cron = this.embeddedValueResolver.resolveStringValue(cron);
					zone = this.embeddedValueResolver.resolveStringValue(zone);
				}
				if (StringUtils.hasLength(cron)) {
					Assert.isTrue(initialDelay == -1, "'initialDelay' not supported for cron triggers");
					processedSchedule = true;
					if (!Scheduled.CRON_DISABLED.equals(cron)) {
						TimeZone timeZone;
						if (StringUtils.hasText(zone)) {
							timeZone = StringUtils.parseTimeZoneString(zone);
						}
						else {
							timeZone = TimeZone.getDefault();
						}
						tasks.add(this.registrar.scheduleCronTask(new CronTask(runnable, new CronTrigger(cron, timeZone))));
					}
				}
			}
            // 第一次延遲參數(shù)小于0,默認為0
			// At this point we don't need to differentiate between initial delay set or not anymore
			if (initialDelay < 0) {
				initialDelay = 0;
			}
			// Check fixed delay 解析fixedDelay參數(shù)
			long fixedDelay = scheduled.fixedDelay();
			if (fixedDelay >= 0) {
				Assert.isTrue(!processedSchedule, errorMessage);
				processedSchedule = true;
				tasks.add(this.registrar.scheduleFixedDelayTask(new FixedDelayTask(runnable, fixedDelay, initialDelay)));
			}
			String fixedDelayString = scheduled.fixedDelayString();
			if (StringUtils.hasText(fixedDelayString)) {
				if (this.embeddedValueResolver != null) {
					fixedDelayString = this.embeddedValueResolver.resolveStringValue(fixedDelayString);
				}
				if (StringUtils.hasLength(fixedDelayString)) {
					Assert.isTrue(!processedSchedule, errorMessage);
					processedSchedule = true;
					try {
						fixedDelay = parseDelayAsLong(fixedDelayString);
					}
					catch (RuntimeException ex) {
						throw new IllegalArgumentException(
								"Invalid fixedDelayString value \"" + fixedDelayString + "\" - cannot parse into long");
					}
					tasks.add(this.registrar.scheduleFixedDelayTask(new FixedDelayTask(runnable, fixedDelay, initialDelay)));
				}
			}
			// Check fixed rate 解析fixedRate參數(shù)
			long fixedRate = scheduled.fixedRate();
			if (fixedRate >= 0) {
				Assert.isTrue(!processedSchedule, errorMessage);
				processedSchedule = true;
				tasks.add(this.registrar.scheduleFixedRateTask(new FixedRateTask(runnable, fixedRate, initialDelay)));
			}
			String fixedRateString = scheduled.fixedRateString();
			if (StringUtils.hasText(fixedRateString)) {
				if (this.embeddedValueResolver != null) {
					fixedRateString = this.embeddedValueResolver.resolveStringValue(fixedRateString);
				}
				if (StringUtils.hasLength(fixedRateString)) {
					Assert.isTrue(!processedSchedule, errorMessage);
					processedSchedule = true;
					try {
						fixedRate = parseDelayAsLong(fixedRateString);
					}
					catch (RuntimeException ex) {
						throw new IllegalArgumentException(
								"Invalid fixedRateString value \"" + fixedRateString + "\" - cannot parse into long");
					}
					tasks.add(this.registrar.scheduleFixedRateTask(new FixedRateTask(runnable, fixedRate, initialDelay)));
				}
			}
			// Check whether we had any attribute set
            // 如果五個參數(shù)一個也沒解析到,拋出異常
			Assert.isTrue(processedSchedule, errorMessage);
			// Finally register the scheduled tasks
            // 并發(fā)控制將任務隊列存入注冊任務列表
			synchronized (this.scheduledTasks) {
				Set<ScheduledTask> regTasks = this.scheduledTasks.computeIfAbsent(bean, key -> new LinkedHashSet<>(4));
				regTasks.addAll(tasks);
			}
		}
		catch (IllegalArgumentException ex) {
			throw new IllegalStateException(
					"Encountered invalid @Scheduled method '" + method.getName() + "': " + ex.getMessage());
		}
	}

將任務解析并添加到任務隊列后,交由ScheduledTaskRegistrar類的scheduleTasks方法添加(注冊)定時任務到環(huán)境中

protected void scheduleTasks() {
   if (this.taskScheduler == null) {
       //獲取ScheduledExecutorService對象,實際上都是使用ScheduledThreadPoolExecutor執(zhí)行定時任務調度
      this.localExecutor = Executors.newSingleThreadScheduledExecutor();
      this.taskScheduler = new ConcurrentTaskScheduler(this.localExecutor);
   }
   if (this.triggerTasks != null) {
      for (TriggerTask task : this.triggerTasks) {
         addScheduledTask(scheduleTriggerTask(task));
      }
   }
   if (this.cronTasks != null) {
      for (CronTask task : this.cronTasks) {
         addScheduledTask(scheduleCronTask(task));
      }
   }
   if (this.fixedRateTasks != null) {
      for (IntervalTask task : this.fixedRateTasks) {
         addScheduledTask(scheduleFixedRateTask(task));
      }
   }
   if (this.fixedDelayTasks != null) {
      for (IntervalTask task : this.fixedDelayTasks) {
         addScheduledTask(scheduleFixedDelayTask(task));
      }
   }
}
private void addScheduledTask(@Nullable ScheduledTask task) {
   if (task != null) {
      this.scheduledTasks.add(task);
   }
}

到此這篇關于Java Spring分別實現(xiàn)定時任務方法的文章就介紹到這了,更多相關Java 定時任務內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

  • Java并發(fā)編程ArrayBlockingQueue的使用

    Java并發(fā)編程ArrayBlockingQueue的使用

    ArrayBlockingQueue是一個備受矚目的有界阻塞隊列,本文將全面深入地介紹ArrayBlockingQueue的內部機制、使用場景以及最佳實踐,感興趣的可以了解一下
    2024-08-08
  • 深入理解Spring Cloud Zuul過濾器

    深入理解Spring Cloud Zuul過濾器

    這篇文章主要給大家介紹了關于Spring Cloud Zuul過濾器的相關資料,通過閱讀本文您將了解:Zuul過濾器類型與請求生命周期、如何編寫Zuul過濾器、如何禁用Zuul過濾器和Spring Cloud為Zuul編寫的過濾器及其功能,需要的朋友可以參考下。
    2017-02-02
  • 使用cmd根據(jù)WSDL網址生成java客戶端代碼的實現(xiàn)

    使用cmd根據(jù)WSDL網址生成java客戶端代碼的實現(xiàn)

    這篇文章主要介紹了使用cmd根據(jù)WSDL網址生成java客戶端代碼的實現(xiàn)方式,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2021-03-03
  • springboot整合spring-retry的實現(xiàn)示例

    springboot整合spring-retry的實現(xiàn)示例

    本文將結合實例代碼,介紹springboot整合spring-retry的實現(xiàn)示例,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2021-06-06
  • Java并發(fā)編程之LongAdder執(zhí)行情況解析

    Java并發(fā)編程之LongAdder執(zhí)行情況解析

    這篇文章主要為大家介紹了Java并發(fā)編程之LongAdder執(zhí)行情況解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2023-04-04
  • IDEA2022.1創(chuàng)建maven項目規(guī)避idea2022新建maven項目卡死無反應問題

    IDEA2022.1創(chuàng)建maven項目規(guī)避idea2022新建maven項目卡死無反應問題

    這篇文章主要介紹了IDEA2022.1創(chuàng)建maven項目規(guī)避idea2022新建maven項目卡死無反應問題,本文通過圖文并茂的形式給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2022-08-08
  • 詳解如何在spring boot中使用spring security防止CSRF攻擊

    詳解如何在spring boot中使用spring security防止CSRF攻擊

    這篇文章主要介紹了詳解如何在spring boot中使用spring security防止CSRF攻擊,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2018-05-05
  • SpringBoot中注冊過濾器的幾種實現(xiàn)方式

    SpringBoot中注冊過濾器的幾種實現(xiàn)方式

    本文主要介紹了SpringBoot中注冊過濾器的幾種實現(xiàn)方式,主要介紹了三種方式,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2024-01-01
  • java中實現(xiàn)自定義注解方式

    java中實現(xiàn)自定義注解方式

    注解是Java中的一種元數(shù)據(jù),可以修飾方法、類、參數(shù)和包等,自定義注解需要public修飾符、@interface關鍵字,以及注解名稱和類型元素,元注解如@Target、@Retention等用于修飾注解,指定注解的適用范圍和生命周期,自定義注解的使用涉及到通過反射解析注解
    2024-11-11
  • Java(JDK/Tomcat/Maven)運行環(huán)境配置及工具(idea/eclipse)安裝詳細教程

    Java(JDK/Tomcat/Maven)運行環(huán)境配置及工具(idea/eclipse)安裝詳細教程

    這篇文章主要介紹了Java(JDK/Tomcat/Maven)運行環(huán)境配置及工具(idea/eclipse)安裝,本文給大家介紹的非常想詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2021-03-03

最新評論

通榆县| 如皋市| 二手房| 炎陵县| 泊头市| 体育| 延寿县| 安庆市| 玉山县| 临桂县| 彭州市| 长垣县| 南京市| 扬州市| 阳原县| 蓬安县| 洮南市| 安多县| 昆明市| 永修县| 四子王旗| 大港区| 浦北县| 额尔古纳市| 江阴市| 尼勒克县| 普兰县| 浮山县| 鱼台县| 兴安盟| 乳山市| 永川市| 阳泉市| 兴化市| 西峡县| 乐都县| 义马市| 大邑县| 荔波县| 南郑县| 秦皇岛市|