`

ScheduledExecutor任务调度

 
阅读更多

鉴于 Timer 的缺陷,Java 5 推出了基于线程池设计的 ScheduledExecutor。其设计思想是,每一个被调度的任务都会由线程池中一个线程去执行,因此任务是并发执行的,相互之间不会受到干扰。需要注意的是,只有当任务的执行时间到来时,ScheduedExecutor 才会真正启动一个线程,其余时间 ScheduledExecutor 都是在轮询任务的状态。


清单 2. 使用 ScheduledExecutor 进行任务调度

 package com.ibm.scheduler;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class ScheduledExecutorTest implements Runnable {
	private String jobName = "";

	public ScheduledExecutorTest(String jobName) {
		super();
		this.jobName = jobName;
	}

	@Override
	public void run() {
		System.out.println("execute " + jobName);
	}

	public static void main(String[] args) {
		ScheduledExecutorService service = Executors.newScheduledThreadPool(10);

		long initialDelay1 = 1;
		long period1 = 1;
        // 从现在开始1秒钟之后,每隔1秒钟执行一次job1
		service.scheduleAtFixedRate(
		        new ScheduledExecutorTest("job1"), initialDelay1,
				period1, TimeUnit.SECONDS);

		long initialDelay2 = 1;
		long delay2 = 1;
        // 从现在开始2秒钟之后,每隔2秒钟执行一次job2
		service.scheduleWithFixedDelay(
		        new ScheduledExecutorTest("job2"), initialDelay2,
				delay2, TimeUnit.SECONDS);
	}
}
Output:
execute job1
execute job1
execute job2
execute job1
execute job1
execute job2

 展示了 ScheduledExecutorService 中两种最常用的调度方法 ScheduleAtFixedRate 和 ScheduleWithFixedDelay。ScheduleAtFixedRate 每次执行时间为上一次任务开始起向后推一个时间间隔,即每次执行时间为 :initialDelay, initialDelay+period, initialDelay+2*period, …;ScheduleWithFixedDelay 每次执行时间为上一次任务结束起向后推一个时间间隔,即每次执行时间为:initialDelay, initialDelay+executeTime+delay, initialDelay+2*executeTime+2*delay。由此可见,ScheduleAtFixedRate 是基于固定时间间隔进行任务调度,ScheduleWithFixedDelay 取决于每次任务执行的时间长短,是基于不固定时间间隔进行任务调度。

分享到:
评论

相关推荐

    几种任务调度的_Java_实现方法与比较

    本文旨在深入探讨几种常见的任务调度在Java中的实现方式,包括`Timer`、`ScheduledExecutor`、开源工具包`Quartz`以及`JCronTab`,并对其特性进行对比分析,以帮助开发者根据具体需求选择最适合的方案。 #### Timer...

    java 任务调度之ScheduledExecutor

    其设计思想是,每一个被调度的任务都会由线程池中一个线程去执行,因此任务是并发执行的,相互之间不会受到干扰。需 要注意的是,只有当任务的执行时间到来时,ScheduedExecutor 才会真正启动一个线程,其余时间 ...

    几种任务调度的用法

    本文将详细介绍几种常见的任务调度技术及其在Java中的实现方式,包括`Timer`、`ScheduledExecutor`、`Quartz`以及`JCronTab`。通过对比这些技术的特点,旨在帮助开发者选择最适合自身需求的任务调度方案。 #### ...

    几种任务调度的Java实现方法与比较

    本文由浅入深介绍四种任务调度的Java实现:ScheduledExecutor开源工具包Quartz开源工具包JCronTab此外,为结合实现复杂的任务调度,本文还将介绍Calendar的一些使用方法。Timer相信大家都已经非常熟悉java.util....

    Java调度原理及使用

    在Java中,有多种方式可以实现任务调度,包括`Timer`、`ScheduledExecutor`以及开源库如`Quartz`和`JCronTab`。 首先,`Timer`类是Java早期提供的定时任务调度器。它的使用非常直观,如代码清单1所示,通过`Timer`...

    Java编程倒计时实现方法示例

    *scheduleAtFixedRate()方法:scheduleAtFixedRate()方法是ScheduleExecutor中的一个方法,用于将任务调度到固定时间间隔执行。 *volatile关键字:volatile关键字是Java中的一个关键字,用于修饰变量,使其在多线程...

Global site tag (gtag.js) - Google Analytics