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)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • idea最新激活码 3月最新注册码

    idea最新激活码 3月最新注册码,https://javaforall.net/100143.html。详细ieda激活码不妨到全栈程序员必看教程网一起来了解一下吧!

    2022年3月14日
    42
  • 编译原理实验一词法分析器_编译原理词法错误举例

    编译原理实验一词法分析器_编译原理词法错误举例编写一个词法分析程序

    2022年9月28日
    2
  • 最经典的黑客入门教程[通俗易懂]

    最经典的黑客入门教程[通俗易懂]第一节、黑客的种类和行为以我的理解,“黑客”大体上应该分为“正”、“邪”两类,正派黑客依靠自己掌握的知识帮助系统管理员找出系统中的漏洞并加以完善,而邪派黑客则是通过各种黑客技能对系统进行攻击、入侵或者做其他一些有害于网络的事情,因为邪派黑客所从事的事情违背了《黑客守则》,所以他们真正的名字叫“骇客”(Cracker)而非“黑客”(Hacker),也就是我们平时经常听说的“黑客”(Cacker)和“红客”(Hacker)。无论那类黑客,他们最初的学习内容都将是本部分所涉及的内容,而且掌握的基本技能也都是.

    2022年6月7日
    34
  • QListWidget的QSS用法「建议收藏」

    QListWidget的QSS用法「建议收藏」本文完全是转载如下网址博客内容,如有侵权,请及时通知,博主会删除。原文地址:https://blog.csdn.net/u011125673/article/details/51753997QListWidget和QTableWidget的使用和属性,QTableWidget和QListWidget样式表的设置,滚动条的样式设置一、QListWidget的使用//一、QListWidgetli…

    2022年6月5日
    315
  • 3DCNN参数解析:2013-PAMI-3DCNN for Human Action Recognition「建议收藏」

    3DCNN参数解析:2013-PAMI-3DCNN for Human Action Recognition「建议收藏」3DCNN参数解析:2013-PAMI-3DCNNforHumanActionRecognition参数分析Input:7@60×\times×40,7帧,图片大小60×\times×40hardwired:H1产生5通道信息,分别是gray,gradient-x,gradient-y,optflow-x,optflow-y。前三个对于每一张图片都计算得…

    2022年6月11日
    43
  • 详解C/C++中volatile关键字「建议收藏」

    详解C/C++中volatile关键字「建议收藏」一、volatile介绍volatile提醒编译器它后面所定义的变量随时都有可能改变,因此编译后的程序每次需要存储或读取这个变量的时候,都会直接从变量地址中读取数据。如果没有volatile关键字,则编译器可能优化读取和存储,可能暂时使用寄存器中的值,如果这个变量由别的程序更新了的话,将出现不一致的现象。下面举例说明。在DSP开发中,经常需要等待某个事件的触发,所以经常会写出这样的程序:这段…

    2022年6月1日
    26

发表回复

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

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