ScheduledExecutorService定时周期执行指定的任务

ScheduledExecutorService定时周期执行指定的任务一:简单说明ScheduleExecutorService接口中有四个重要的方法,其中scheduleAtFixedRate和scheduleWithFixedDelay在实现定时程序时比较方便。下面是该接口的原型定义java.util.concurrent.ScheduleExecutorServiceextends ExecutorServiceextends Execut

大家好,又见面了,我是你们的朋友全栈君。

一:简单说明

ScheduleExecutorService接口中有四个重要的方法,其中scheduleAtFixedRate和scheduleWithFixedDelay在实现定时程序时比较方便。

下面是该接口的原型定义

java.util.concurrent.ScheduleExecutorService extends ExecutorService extends Executor

ScheduledExecutorService定时周期执行指定的任务

接口scheduleAtFixedRate原型定义及参数说明

 public ScheduledFuture<?> scheduleAtFixedRate(Runnable command,
				long initialDelay,
				long period,
				TimeUnit unit);

command:执行线程
initialDelay:初始化延时
period:两次开始执行最小间隔时间
unit:计时单位

接口scheduleWithFixedDelay原型定义及参数说明

public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command,
				long initialDelay,
				long delay,
				TimeUnit unit);

command:执行线程
initialDelay:初始化延时
period:前一次执行结束到下一次执行开始的间隔时间(间隔执行延迟时间)
unit:计时单位

二:功能示例

1.按指定频率周期执行某个任务。

初始化延迟0ms开始执行,每隔100ms重新执行一次任务。

/**
 * 以固定周期频率执行任务
 */
public static void executeFixedRate() {
	ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
	executor.scheduleAtFixedRate(
			new EchoServer(),
			0,
			100,
			TimeUnit.MILLISECONDS);
}

间隔指的是连续两次任务开始执行的间隔。

2.按指定频率间隔执行某个任务。

初始化时延时0ms开始执行,本次执行结束后延迟100ms开始下次执行。

/**
 * 以固定延迟时间进行执行
 * 本次任务执行完成后,需要延迟设定的延迟时间,才会执行新的任务
 */
public static void executeFixedDelay() {
	ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
	executor.scheduleWithFixedDelay(
			new EchoServer(),
			0,
			100,
			TimeUnit.MILLISECONDS);
}

3.周期定时执行某个任务。

有时候我们希望一个任务被安排在凌晨3点(访问较少时)周期性的执行一个比较耗费资源的任务,可以使用下面方法设定每天在固定时间执行一次任务。

/**
 * 每天晚上8点执行一次
 * 每天定时安排任务进行执行
 */
public static void executeEightAtNightPerDay() {
	ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
	long oneDay = 24 * 60 * 60 * 1000;
	long initDelay  = getTimeMillis("20:00:00") - System.currentTimeMillis();
	initDelay = initDelay > 0 ? initDelay : oneDay + initDelay;

	executor.scheduleAtFixedRate(
			new EchoServer(),
			initDelay,
			oneDay,
			TimeUnit.MILLISECONDS);
}
/**
 * 获取指定时间对应的毫秒数
 * @param time "HH:mm:ss"
 * @return
 */
private static long getTimeMillis(String time) {
	try {
		DateFormat dateFormat = new SimpleDateFormat("yy-MM-dd HH:mm:ss");
		DateFormat dayFormat = new SimpleDateFormat("yy-MM-dd");
		Date curDate = dateFormat.parse(dayFormat.format(new Date()) + " " + time);
		return curDate.getTime();
	} catch (ParseException e) {
		e.printStackTrace();
	}
	return 0;
}

4.辅助代码

class EchoServer implements Runnable {
	@Override
	public void run() {
		try {
			Thread.sleep(50);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.println("This is a echo server. The current time is " +
				System.currentTimeMillis() + ".");
	}
}

三:一些问题

上面写的内容有不严谨的地方,比如对于scheduleAtFixedRate方法,当我们要执行的任务大于我们指定的执行间隔时会怎么样呢?

对于中文API中的注释,我们可能会被忽悠,认为无论怎么样,它都会按照我们指定的间隔进行执行,其实当执行任务的时间大于我们指定的间隔时间时,它并不会在指定间隔时开辟一个新的线程并发执行这个任务。而是等待该线程执行完毕。

源码注释如下:

* Creates and executes a periodic action that becomes enabled first
* after the given initial delay, and subsequently with the given
* period; that is executions will commence after
* <tt>initialDelay</tt> then <tt>initialDelay+period</tt>, then
* <tt>initialDelay + 2 * period</tt>, and so on.
* If any execution of the task
* encounters an exception, subsequent executions are suppressed.
* Otherwise, the task will only terminate via cancellation or
* termination of the executor.  If any execution of this task
* takes longer than its period, then subsequent executions
* may start late, but will not concurrently execute.

根据注释中的内容,我们需要注意的时,我们需要捕获最上层的异常,防止出现异常中止执行,导致周期性的任务不再执行。

四:除了我们自己实现定时任务之外,我们可以使用Spring帮我们完成这样的事情。

Spring自动定时任务配置方法(我们要执行任务的类名为com.study.MyTimedTask)

<bean id="myTimedTask" class="com.study.MyTimedTask"/>

<bean id="doMyTimedTask" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
	<property name="targetObject" ref="myTimedTask"/>
	<property name="targetMethod" value="execute"/>
	<property name="concurrent" value="false"/>
</bean>

<bean id="myTimedTaskTrigger" class="org.springframework.scheduling.quartz.CronTriggerBean">
	<property name="jobDetail" ref="doMyTimedTask"/>
	<property name="cronExpression" value="0 0 2 * ?"/>
</bean>

<bean id="doScheduler" class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
	<property name="triggers">
		<list>
			<ref local="myTimedTaskTrigger"/>
		</list>
	</property>
</bean>

<bean id="doScheduler" class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
	<property name="triggers">
		<list>
			<bean class="org.springframework.scheduling.quartz.CronTriggerBean">
				<property name="jobDetail"/>
					<bean id="doMyTimedTask" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
						<property name="targetObject">
							<bean class="com.study.MyTimedTask"/>
						</property>
						<property name="targetMethod" value="execute"/>
						<property name="concurrent" value="false"/>
					</bean>
				</property>
				<property name="cronExpression" value="0 0 2 * ?"/>
			</bean>
		</list>
	</property>
</bean>

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/137044.html原文链接:https://javaforall.net

赞 (0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • 怎么html文字下划线,HTML怎么设置下划线?html文字加下划线方法

    怎么html文字下划线,HTML怎么设置下划线?html文字加下划线方法HTML中的下划线曾经是将文本包含在标签中的问题,但是这种方法已被放弃,而更倾向于使用更多功能的CSS。一般来说,下划线被认为是引起人们对文本注意的一种方式,那么HTML怎么设置下划线?html文字加下划线方法?下面我们来总结一下。1.使用“text-decoration”CSS样式属性,使用标签不再是强调文本的正确方法。而是使用“text-decoration”CSS属性,语法为:<sp…

    2022年6月3日
  • 视频标清、高清、全高清的分类分辨率码率帧率参考(附图)

    视频标清、高清、全高清的分类分辨率码率帧率参考(附图)视频标清、高清、全高清的分类分辨率码率帧率参考(附图)视频标清、高清、全高清的分类分辨率码率帧率参考(附图)

    2022年5月6日
  • 设计模式——六大原则[通俗易懂]

    设计模式——六大原则[通俗易懂]设计模式——六大原则

    2022年4月24日
  • stm32使用oled显示屏_stm32f103c8t6封装

    stm32使用oled显示屏_stm32f103c8t6封装stm32f103c8t6控制OLED显示屏0.96寸4针OLED显示屏IIC蓝色0.96寸OLED显示屏7针SPI蓝色,6针黄蓝双色0.96寸4针OLED显示屏IIC蓝色话不多说,直接先上图!显然可以看出,利用IIC接口显示出来的文字是没那么清晰的,有点断断续续的。而这款显示屏我是买淘宝上这家店的,下面附上这个显示屏链接:0.96寸4针OLED显示屏IIC蓝色附上显示屏与stm32的接线://功能描述:OLEDI2C接口演示例程(STM32F103系列)//

    2022年10月15日
  • 13个Python GUI库

    13个Python GUI库PythonPython是一门高级编程语言。它用于通用编程。Python语言由GuidovanRossum创建,并于1991年首次发布。Python的设计哲学着重于代码的可读性。因此空白在Python中具有重要的意义。Python提供了允许在小规模和大规模上编程的设计理念,而且具有一个非常庞大的标准库。Python使用动态类型系统,并具有自动内存管理功能。更多Python视…

    2022年7月20日
  • MOS管电平转换电路学习

    MOS管电平转换电路学习一个MOSFET电平转换电路引发的问题

    2022年10月19日

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号