使用Timer和ScheduledThreadPoolExecutor执行定时任务
Java使用Timer和ScheduledThreadPoolExecutor执行定时任务
定时任务是在指定时间执行程序,或周期性执行计划任务。Java中实现定时任务的方法有很多,主要JDK自带的一些方法以及开源程序如Qurtz。
>>Timer和TimerTask
Timer只是充当了一个执行者的角色,真正的任务逻辑是通过一个叫做TimerTask的抽象类完成的,TimerTask也是java.util包下面的类,
它是一个实现了Runnable接口的抽象类,包含一个抽象方法run( )方法,需要我们自己去提供具体的业务实现。
Timer 的优点在于简单易用,但由于所有任务都是由同一个线程来调度,
因此所有任务都是串行执行的,同一时间只能有一个任务在执行,前一个任务的延迟或异常都将会影响到之后的任务。
示例代码:
public class TimerTest {
//被执行的任务必须继承TimerTask,并且实现run方法
static class MyTimerTask1 extends TimerTask {
public void run() {
System.out.println("执行当前线程"+Thread.currentThread().getName());
}
}
/**
* Timer线程不会捕获异常,所以TimerTask抛出的未检查的异常会终止timer线程。
* 如果Timer线程中存在多个计划任务,其中一个计划任务抛出未检查的异常,则会引起整个Timer线程结束,从而导致其他计划任务无法得到继续执行。
* Timer线程时基于绝对时间,因此计划任务对系统的时间的改变是敏感的。
* Timer是单线程,如果某个任务很耗时,可能会影响其他计划任务的执行。
* @param args
* @throws ParseException
* @throws InterruptedException
*/
public static void main(String[] args) throws ParseException, InterruptedException {
Timer timer = new Timer();
/**
* scheduleAtFixedRate方式
* 设定两秒后执行任务
*/
timer.scheduleAtFixedRate(new MyTimerTask1(), 2000,1000);
/**
* schedule添加Date参数
* 设定任务在执行时间执行
*/
// SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
// Date time = dateFormatter.parse("2016/03/28 14:40:00");
// timer.schedule(new MyTimerTask1(), time);
//启动MyTimerTask1线程后,主线程休眠五秒钟,给MyTimerTask1五秒的执行时间
Thread.sleep(5000);
//终止Timer线程
timer.cancel();
}
}
JDK 5.0以后推荐使用ScheduledThreadPoolExecutor。关于Timer简单了解即可。
>>ScheduledThreadPoolExecutor
ScheduledThreadPoolExecutor属于Executor Framework,
它除了能处理异常外,还可以以多线程方式执行定时任务。
Timer类是通过单线程来执行所有的TimerTask任务的,如果一个任务的执行过程非常耗时,将会导致其他任务的时效性出现问题。
而 ScheduledThreadPoolExecutor是基于线程池的多线程执行任务,不会存在这样的问题。
通过一个实例学习:
public class ScheduledThreadPoolExecutorTest {
public static void main(String[] args) {
//获得实例,并且设置它的容量为5个
ScheduledThreadPoolExecutor sExecutor=new ScheduledThreadPoolExecutor(5);
MyTask task = new MyTask();
//隔2秒后开始执行任务,并且在上一次任务开始后隔一秒再执行一次
// sExecutor.scheduleWithFixedDelay(task, 2, 1, TimeUnit.SECONDS);
//隔6秒后执行一次,但只会执行一次
sExecutor.schedule(task, 6, TimeUnit.SECONDS);
/**
* 和Timer类似,也可以直接在任务的run()方法中调用调度方法停止
* 这个方法会平滑的关闭调度器,等待所有任务结束
*/
sExecutor.shutdown();
}
static class MyTask implements Runnable{
@Override
public void run() {
System.out.println("当前执行的线程"+Thread.currentThread().getName());
}
}
}
>>使用Qurtz
Qurtz的使用非常简单,作为解决方案支持更多的触发机制,具体的应用谷歌一下,你就知道。
使用Timer和ScheduledThreadPoolExecutor执行定时任务的更多相关文章
- 使用ScheduledThreadPoolExecutor执行定时任务
ScheduledThreadPoolExecutor scheduled = new ScheduledThreadPoolExecutor(2); scheduled.scheduleAtFixe ...
- timer和ScheduledThreadPoolExecutor定时任务和每日固定时间执行
//ScheduledThreadPoolExecutor每三秒执行一次 public static void main(String[] args) { ScheduledThread ...
- 服务器启动完成执行定时任务Timer,TimerTask
由于项目需求:每隔一段时间就要调外部接口去进行某些操作,于是在网上找了一些资料,用了半天时间弄好了,代码: import java.util.TimerTask; public class Accou ...
- java关于Timer schedule执行定时任务 !!!!!!!!!
1.在应用开发中,经常需要一些周期性的操作,比如每5分钟执行某一操作等.对于这样的操作最方便.高效的实现方式就是使用java.util.Timer工具类. private java.util.Time ...
- java关于Timer schedule执行定时任务 1、在应用开发中,经常需要一些周期性的操作,比如每5分钟执行某一操作等
1.在应用开发中,经常需要一些周期性的操作,比如每5分钟执行某一操作等.对于这样的操作最方便.高效的实现方式就是使用java.util.Timer工具类. private java.util.Time ...
- Timer和ScheduledThreadPoolExecutor的区别
Timer 基于单线程.系统时间实现的延时.定期任务执行类.具体可以看下面红色标注的代码. public class Timer { /** * The timer task queue. This ...
- java中服务器启动时,执行定时任务
package com.ripsoft.util; import java.util.Calendar; import java.util.Timer; import javax.servlet.Se ...
- .NET Core中使用IHostedService结合队列执行定时任务
最近遇到了这样的场景:每隔一段时间,需要在后台使用队列对一批数据进行业务处理. Quartz.NET是一种选择,在 .NET Core中,可以使用IHostedService执行后台定时任务.在本篇中 ...
- 使用Quartz.net来执行定时任务
Quartz.net使用方法:http://www.cnblogs.com/lizichao1991/p/5707604.html 最近,项目中需要执行一个计划任务,组长就让我了解一下Quartz.n ...
随机推荐
- caffe学习系列(5):激活层介绍
参考:http://www.cnblogs.com/denny402/p/5072507.html 主要介绍了各个激活函数.
- linux kernel 平台总线实例分析
linux 平台总线的实现有三大块 , platform bus , platform device , platform drvice 平台类型结构体: /** * struct bus_type ...
- openstacksdk enable logging
http://git.openstack.org/cgit/openstack/python-openstacksdk/tree/doc/source/users/guides/logging.rst
- OpenStack网络指导手册 -基本网络概念
转自:http://blog.csdn.net/zztflyer/article/details/50441200 目录(?)[-] 以太网Ethernet 虚拟局域网VLANs 子网和地址解析协议S ...
- struts2 模型驱动
public class User3Action extends ActionSupport implements ModelDriven<User> { private User use ...
- 常见概率组合题目总结quickstart
[本文链接] http://www.cnblogs.com/hellogiser/p/interview-questions-quickstart-for-combination-permutatio ...
- Debian Vi 简介
1.Vi 简介 Vi 是 Unix 世界里极为普遍的全萤幕文书编辑器,几乎可以说任何一台 Unix 机器都会提供这套软体.Linux 当然也有,它的 vi 其实是 elvis (版权问题),不 ...
- ubuntu vsftp 安装
1.输入sudo apt-get install vsftpd 回车 这样就安装完毕了,然后去建立一个ftp的帐号,我这里使用的是ftp. 2.输入useradd ftp 回车 输入密码 回车 这样帐 ...
- Divide and conquer:Matrix(POJ 3685)
矩阵 题目大意:矩阵里面的元素按i*i + 100000 * i + j*j - 100000 * j + i*j填充(i是行,j是列),求最小的M个数 这一题要用到两次二分,实在是二分法的经典,主要 ...
- 【leetcode】Implement strStr() (easy)
Implement strStr(). Returns the index of the first occurrence of needle in haystack, or -1 if needle ...