定时任务-ScheduledExecutorService
创建定时任务线程池的方式
ScheduledExecutorService executorService = Executors.newScheduledThreadPool(4);// 不推荐
// 或
ScheduledExecutorService executorService = new ScheduledThreadPoolExecutor(4);// 推荐
创建定时任务的方法
public interface ScheduledExecutorService extends ExecutorService {
/**
* 延迟delay(时间单位由unit指定)后执行任务
*
* @param command 任务
* @param delay 延迟时间
* @param unit 时间单位
* @return 执行结果
*/
public ScheduledFuture<?> schedule(Runnable command, long delay, TimeUnit unit);
/**
* 延迟delay(时间单位由unit指定)时间后执行任务
* 任务执行完毕后,返回执行结果
*
* @param callable 任务
* @param delay 延迟时间
* @param unit 时间单位
* @return 执行结果
*/
public <V> ScheduledFuture<V> schedule(Callable<V> callable, long delay, TimeUnit unit);
/**
* 延迟delay时间后执行第一次任务,之后每过period毫秒执行一次。
* 假设:
* 执行一次任务需要消耗的时间为 exeTime
* 执行此次任务的开始时间是 nowTime
* 执行下一次任务的实际时间是 actuallyTime
* 如果 exeTime >= period ,那么,actuallyTime >= nowTime + exeTime;
* 如果 exeTime < period , 那么,actuallyTime >= nowTime + period;
*
* @param command 任务
* @param initialDelay 执行首次任务之前的延时时间
* @param period 周期性执行任务,相邻两次的时间间隔
* @param unit 时间单位
* @return 执行结果
*/
public ScheduledFuture<?> scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit);
/**
* 延迟initialDelay时间后执行首次任务,之后的任务执行,全部在上次任务执行完毕之后,再延迟delay时间执行。
*
* 假设:
* 执行一次任务需要消耗的时间为 exeTime
* 执行此次任务的开始时间是 nowTime
* 执行下一次任务的实际时间是 actuallyTime
* 如果 exeTime >= period ,那么,actuallyTime >= nowTime + exeTime + delay;
* 如果 exeTime < period , 那么,actuallyTime >= nowTime + exeTime + period;
*
* @param command 任务
* @param initialDelay 执行首次任务之前的延迟时间
* @param delay 每次任务执行完成后,执行下次任务之前的延迟时间
* @param unit 时间单位
* @return
*/
public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit);
}
创建定时任务的示例
示例一:延迟执行
package com.java.scheduled.task.pool; import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit; public class ScheduledTaskDemo01 { public static void main(String[] args) {
ScheduledExecutorService executorService = new ScheduledThreadPoolExecutor(4);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = new Date();
System.out.println("安排执行任务的时间:"+sdf.format(date));
long c1 = date.getTime();
Runnable runnable = () -> {
Date nowDate = new Date();
System.out.println("****计划任务(1):【延迟2秒执行】");
System.out.println("实际执行任务的时间:"+sdf.format(nowDate));
System.out.println("延迟时间:"+(nowDate.getTime() - c1)+"ms");
};
executorService.schedule(runnable, 2, TimeUnit.SECONDS);
} }
执行结果如下:
安排执行任务的时间:2019-05-28 12:10:46
****计划任务(1):【延迟2秒执行】
实际执行任务的时间:2019-05-28 12:10:48
延迟时间:2087ms
示例二:延迟执行,返回结果
package com.java.scheduled.task.pool; import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.*; public class ScheduledTaskDemo02 { public static void main(String[] args) {
ScheduledExecutorService executorService = Executors.newScheduledThreadPool(4);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = new Date();
System.out.println("安排执行任务的时间:"+sdf.format(date));
long c2 = date.getTime();
Callable<String> callable = () -> {
Date nowDate = new Date();
System.out.println("****计划任务(2):【延迟2秒执行,执行结束返回结果】");
System.out.println("实际执行任务的时间:"+sdf.format(nowDate));
System.out.println("延迟时间:"+(nowDate.getTime() - c2)+"ms");
Thread.sleep(1000);
System.out.println("任务执行完毕,当前时间:"+sdf.format(new Date()));
return "success";
};
ScheduledFuture<String> scheduledFuture = executorService.schedule(callable, 2, TimeUnit.SECONDS);
try {
System.out.println("任务的执行结果:"+scheduledFuture.get());
} catch (ExecutionException e1) {
e1.printStackTrace();
} catch (InterruptedException e2) {
e2.printStackTrace();
}
} }
执行结果如下:
安排执行任务的时间:2019-05-28 12:14:05
****计划任务(2):【延迟2秒执行,执行结束返回结果】
实际执行任务的时间:2019-05-28 12:14:07
延迟时间:2072ms
任务执行完毕,当前时间:2019-05-28 12:14:08
任务的执行结果:success
示例三:延迟+周期性执行任务
package com.java.scheduled.task.pool; import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit; public class ScheduledTaskDemo03 { public static void main(String[] args) {
ScheduledExecutorService executorService = Executors.newScheduledThreadPool(4);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = new Date();
System.out.println("安排执行任务的时间:"+sdf.format(date));
long c3 = date.getTime();
Runnable runnable = new Runnable() {
long exeTime = c3;
@Override
public void run() {
Date nowDate = new Date();
System.out.println("--------------------------------------------------------------------------------");
System.out.println("计划任务(3):【延迟1秒执行第一次任务,之后每过2秒执行一次任务】");
System.out.println("****实际执行任务的时间:"+sdf.format(nowDate));
System.out.println("****距离上次执行任务的时间间隔:"+(nowDate.getTime() - exeTime)+"ms");
try {
Thread.sleep(4000);
} catch (InterruptedException e) {}
exeTime = nowDate.getTime();
}
};
executorService.scheduleAtFixedRate(runnable, 1, 2, TimeUnit.SECONDS);
} }
执行结果如下:
安排执行任务的时间:2019-05-28 12:15:12
--------------------------------------------------------------------------------
计划任务(3):【延迟1秒执行第一次任务,之后每过2秒执行一次任务】
****实际执行任务的时间:2019-05-28 12:15:13
****距离上次执行任务的时间间隔:1003ms
--------------------------------------------------------------------------------
计划任务(3):【延迟1秒执行第一次任务,之后每过2秒执行一次任务】
****实际执行任务的时间:2019-05-28 12:15:17
****距离上次执行任务的时间间隔:4002ms
--------------------------------------------------------------------------------
计划任务(3):【延迟1秒执行第一次任务,之后每过2秒执行一次任务】
****实际执行任务的时间:2019-05-28 12:15:21
****距离上次执行任务的时间间隔:4001ms
--------------------------------------------------------------------------------
计划任务(3):【延迟1秒执行第一次任务,之后每过2秒执行一次任务】
****实际执行任务的时间:2019-05-28 12:15:25
****距离上次执行任务的时间间隔:4002ms
示例四:初始延迟+周期性延迟执行任务
package com.java.scheduled.task.pool; import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit; public class ScheduledTaskDemo04 { public static void main(String[] args) {
ScheduledExecutorService executorService = Executors.newScheduledThreadPool(4);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = new Date();
System.out.println("安排执行任务的时间:"+sdf.format(date));
long c3 = date.getTime();
Runnable runnable = new Runnable() {
long exeTime = c3;
@Override
public void run() {
Date nowDate = new Date();
System.out.println("--------------------------------------------------------------------------------");
System.out.println("计划任务(4):【延迟1秒执行第一次任务,之后每过2秒执行一次任务】");
System.out.println("****实际执行任务的时间:"+sdf.format(nowDate));
System.out.println("****距离上次执行任务的时间间隔:"+(nowDate.getTime() - exeTime)+"ms");
try {
Thread.sleep(2500);
} catch (InterruptedException e) {}
exeTime = nowDate.getTime();
}
};
executorService.scheduleWithFixedDelay(runnable, 1, 2, TimeUnit.SECONDS);
} }
执行结果如下:
安排执行任务的时间:2019-05-28 12:16:56
--------------------------------------------------------------------------------
计划任务(4):【延迟1秒执行第一次任务,之后每过2秒执行一次任务】
****实际执行任务的时间:2019-05-28 12:16:57
****距离上次执行任务的时间间隔:1018ms
--------------------------------------------------------------------------------
计划任务(4):【延迟1秒执行第一次任务,之后每过2秒执行一次任务】
****实际执行任务的时间:2019-05-28 12:17:01
****距离上次执行任务的时间间隔:4504ms
--------------------------------------------------------------------------------
计划任务(4):【延迟1秒执行第一次任务,之后每过2秒执行一次任务】
****实际执行任务的时间:2019-05-28 12:17:06
****距离上次执行任务的时间间隔:4502ms
--------------------------------------------------------------------------------
计划任务(4):【延迟1秒执行第一次任务,之后每过2秒执行一次任务】
****实际执行任务的时间:2019-05-28 12:17:10
****距离上次执行任务的时间间隔:4502ms
定时任务-ScheduledExecutorService的更多相关文章
- <线程池-定时任务> ScheduledExecutorService之shutdown引发的RejectedExecutionException问题
一. 问题描述 先来看一下异常信息,启动tomcat时就报错: 2015-3-20 15:22:39 org.apache.catalina.core.StandardContext listener ...
- java 多线程:线程池的使用Executors~ExecutorService; newCachedThreadPool;newFixedThreadPool(int threadNum);ScheduledExecutorService
1,为什么要使用线程池:Executors 系统启动一个新线程的成本是比较高的,因为它涉及与操作系统交互.在这种情形下,使用线程池可以很好地提高性能,尤其是当程序中需要创建大量生存期很短暂的线程时,更 ...
- Android解析XML文件
XML文件和获取XML值 XML文件样例 <?xml version="1.0" encoding="utf-8"?> <citys> ...
- eureka client服务续约源码分析
必备知识: 1.定时任务 ScheduledExecutorService public class demo { public static void main(String[] args){ Sc ...
- 日记整理---->2016-11-21
2016-11-21简单的总结一下学到的知识点.作为一个目标而存在的东西,总是那么美丽而优雅. 一.PE中事务的编写 getTransactionTemplate().execute(new Tran ...
- java定时任务接口ScheduledExecutorService
一.ScheduledExecutorService 设计思想 ScheduledExecutorService,是基于线程池设计的定时任务类,每个调度任务都会分配到线程池中的一个线程去执行,也就是说 ...
- java定时任务Timer与ScheduledExecutorService<转>
在我们编程过程中如果需要执行一些简单的定时任务,无须做复杂的控制,我们可以考虑使用JDK中的Timer定时任务来实现.下面LZ就其原理.实例以及Timer缺陷三个方面来解析java Timer定时器. ...
- spring boot.定时任务问题记录(TaskScheduler/ScheduledExecutorService异常)
一.背景 spring boot的定时任务非常简单,只需要在启动类中加上@EnableScheduling注解,然后在对应的方法上配置@Scheduled就可以了,系统会自动处理并按照Schedule ...
- Executors框架之ScheduledExecutorService实现定时任务
一.简介 An ExecutorService that can schedule commands to run after a given delay, or to execute periodi ...
随机推荐
- 【python】string functions
1.str.replace(word0,word1) ##用word1替换str中所有的word0 >>> 'tea for too'.replace('too', 'two') ...
- MVC错误:查询的结果不能枚举多次
应用程序中的服务器错误. 查询的结果不能枚举多次. 说明: 执行当前 Web 请求期间,出现未经处理的异常.请检查堆栈跟踪信息,以了解有关该错误以及代码中导致错误的出处的详细信息. 异常详细信息: S ...
- 华为CodeCraft2018 周进展
上周: python验证lstm,效果不好.很多拟合的是直线.C++抄了个lstm,输出也是直线,不知道是程序的问题,还是模型的问题. 尝试bp神经网络求解.代码是抄的.回看天数是写死的,隐层只有一层 ...
- java集合框架之Collection
参考http://how2j.cn/k/collection/collection-collection/366.html Collection是 Set List Queue和 Deque的接口Qu ...
- TypeScript完全解读(26课时)_3.TypeScript完全解读-Symbol
ts中symbol的支持是按照es6的标准来的,只要我们学会es6中的symbol,就可以直接在ts中使用了 创建symbol 在example文件夹下新建symbol.ts 然后在根目录的index ...
- Swift3.0 Set
set的简单的使用方法 //创建一个空set var letters = Set<Character>() //数组字面量创建set,只能存放string var setColors:Se ...
- 手游性能优化之深入理解Texture Compression
http://gad.qq.com/article/detail/7154875 一.引子 手游项目开发日常里,经常有美术同学搞不清Photoshop制图软件与Unity3D游戏引擎之间的图片asse ...
- Unity的http通信--unity与python的django通信
http://blog.csdn.net/chenggong2dm/article/details/17372203 写在前面: WWW类,是unity里,简单的访问网页的类.本文介绍的就是这种方式, ...
- 如何在内网打洞使得能暴露mstsc端口
说明: 1.目标机器Target,有全部控制权,其所处网络无法向外网暴露端口,但是已知Target的外网地址:Target_internet_addr 2.交换机器Exchange,有全部控制权,其所 ...
- 51nod1086(多重背包&二進制)
題目鏈接:http://www.51nod.com/onlineJudge/questionCode.html#!problemId=1086 題意:中文題誒- 思路:很顯然這是一道多重背包題,不過這 ...