ScheduledExecutorService执行周期任务 (转)

这两天 用ScheduledExecutorService定期执行一些任务。查阅相关资料来看这个类怎么用。

 

启动定时任务可以见下面的文章,可是关于启动任务后,怎么随时停止指定的任务,查了查一些资料,原来这么用。

调用 scheduleWithFixedDelay()方法会返回一个Future类型的 返回值。我们可以将该future保存起来。当需要终止某个任务时,将对应的future  取出来,执行 future.cancel(true/false)  即可停止该任务的执行。

 

如果要停掉这个定时服务线程池,可以调用shutdown或shutdownNow。

一个ScheduledExecutorService 执行shutdown后,不能再执行 新的任务了,当前运行的任务继续完成,等待的任务不再执行。再执行新任务时,需要我们 重新创建线程池。

执行shutdownNow会强行关掉正在运行的任务(可能会抛出InterruptedException)及取消等待的任务。不能再执行 新的任务了

 

-------------------------------------下面的转载

 

 

 

 

 

一:简单说明

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

下面是该接口的原型定义

java.util.concurrent.ScheduleExecutorService extends ExecutorService extends Executor

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

  1. public ScheduledFuture<?> scheduleAtFixedRate(Runnable command,  
  2.             long initialDelay,  
  3.             long period,  
  4.             TimeUnit unit);  
 public ScheduledFuture<?> scheduleAtFixedRate(Runnable command,
				long initialDelay,
				long period,
				TimeUnit unit);

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

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

  1. public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command,  
  2.                 long initialDelay,  
  3.                 long delay,  
  4.                 TimeUnit unit);  
public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command,
				long initialDelay,
				long delay,
				TimeUnit unit);

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

二:功能示例

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

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

  1. /** 
  2.  * 以固定周期频率执行任务 
  3.  */  
  4. public static void executeFixedRate() {  
  5.     ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);  
  6.     executor.scheduleAtFixedRate(  
  7.             new EchoServer(),  
  8.             0,  
  9.             100,  
  10.             TimeUnit.MILLISECONDS);  
  11. }  
/**
 * 以固定周期频率执行任务
 */
public static void executeFixedRate() {
	ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
	executor.scheduleAtFixedRate(
			new EchoServer(),
			0,
			100,
			TimeUnit.MILLISECONDS);
}

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

 

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

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

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

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

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

  1. /** 
  2.  * 每天晚上8点执行一次 
  3.  * 每天定时安排任务进行执行 
  4.  */  
  5. public static void executeEightAtNightPerDay() {  
  6.     ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);  
  7.     long oneDay = 24 * 60 * 60 * 1000;  
  8.     long initDelay  = getTimeMillis("20:00:00") - System.currentTimeMillis();  
  9.     initDelay = initDelay > 0 ? initDelay : oneDay + initDelay;  
  10.   
  11.     executor.scheduleAtFixedRate(  
  12.             new EchoServer(),  
  13.             initDelay,  
  14.             oneDay,  
  15.             TimeUnit.MILLISECONDS);  
  16. }  
/**
 * 每天晚上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);
}
  1. /** 
  2.  * 获取指定时间对应的毫秒数 
  3.  * @param time "HH:mm:ss" 
  4.  * @return 
  5.  */  
  6. private static long getTimeMillis(String time) {  
  7.     try {  
  8.         DateFormat dateFormat = new SimpleDateFormat("yy-MM-dd HH:mm:ss");  
  9.         DateFormat dayFormat = new SimpleDateFormat("yy-MM-dd");  
  10.         Date curDate = dateFormat.parse(dayFormat.format(new Date()) + " " + time);  
  11.         return curDate.getTime();  
  12.     } catch (ParseException e) {  
  13.         e.printStackTrace();  
  14.     }  
  15.     return 0;  
  16. }  
/**
 * 获取指定时间对应的毫秒数
 * @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.辅助代码

  1. class EchoServer implements Runnable {  
  2.     @Override  
  3.     public void run() {  
  4.         try {  
  5.             Thread.sleep(50);  
  6.         } catch (InterruptedException e) {  
  7.             e.printStackTrace();  
  8.         }  
  9.         System.out.println("This is a echo server. The current time is " +  
  10.                 System.currentTimeMillis() + ".");  
  11.     }  
  12. }  
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中的注释,我们可能会被忽悠,认为无论怎么样,它都会按照我们指定的间隔进行执行,其实当执行任务的时间大于我们指定的间隔时间时,它并不会在指定间隔时开辟一个新的线程并发执行这个任务。而是等待该线程执行完毕。

源码注释如下:

 

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

 

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

 

  1. <bean id="doMyTimedTask" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">  
  2.     <property name="targetObject" ref="myTimedTask"/>  
  3.     <property name="targetMethod" value="execute"/>  
  4.     <property name="concurrent" value="false"/>  
  5. </bean>  
<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>

 

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

 

  1. <bean id="doScheduler" class="org.springframework.scheduling.quartz.SchedulerFactoryBean">  
  2.     <property name="triggers">  
  3.         <list>  
  4.             <ref local="myTimedTaskTrigger"/>  
  5.         </list>  
  6.     </property>  
  7. </bean>  
<bean id="doScheduler" class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
	<property name="triggers">
		<list>
			<ref local="myTimedTaskTrigger"/>
		</list>
	</property>
</bean>

 

  1. <bean id="doScheduler" class="org.springframework.scheduling.quartz.SchedulerFactoryBean">  
  2.     <property name="triggers">  
  3.         <list>  
  4.             <bean class="org.springframework.scheduling.quartz.CronTriggerBean">  
  5.                 <property name="jobDetail"/>  
  6.                     <bean id="doMyTimedTask" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">  
  7.                         <property name="targetObject">  
  8.                             <bean class="com.study.MyTimedTask"/>  
  9.                         </property>  
  10.                         <property name="targetMethod" value="execute"/>  
  11.                         <property name="concurrent" value="false"/>  
  12.                     </bean>  
  13.                 </property>  
  14.                 <property name="cronExpression" value="0 0 2 * ?"/>  
  15.             </bean>  
  16.         </list>  
  17.     </property>  
  18. </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>

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
ScheduledExecutorServiceJava中的一个接口,它是ExecutorService的子接口,用于在指定的时间间隔内执行任务。它可以用来执行定时任务周期任务以及延迟任务。 要获取ScheduledExecutorService任务返回结果,可以使用Future接口。Future接口表示一个异步计算的结果,可以通过它来获取任务执行结果。 首先,我们需要使用ScheduledExecutorService的submit方法来提交任务,并将返回Future对象保存起来。然后,可以使用Future对象的get方法来获取任务返回结果。get方法是一个阻塞方法,会一直等待任务执行完成并返回结果。 下面是一个示例代码: ```java import java.util.concurrent.*; public class ScheduledExecutorServiceExample { public static void main(String[] args) throws InterruptedException, ExecutionException { ScheduledExecutorService executor = Executors.newScheduledThreadPool(1); // 提交任务并获取Future对象 Future<String> future = executor.schedule(() -> { // 任务逻辑 return "Hello, World!"; }, 1, TimeUnit.SECONDS); // 获取任务返回结果 String result = future.get(); System.out.println(result); executor.shutdown(); } } ``` 在上面的示例中,我们创建了一个ScheduledExecutorService对象,并使用schedule方法提交了一个任务。该任务会在1秒后执行,并返回字符串"Hello, World!"。然后,我们使用Future对象的get方法获取任务返回结果,并打印输出。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值