使用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 ...
随机推荐
- linux下使用rdp
简单的说就是在linux下如何远程终端连接一台windows的服务器. 在windwos下我们直接可以mstsc开启远程终端的连接.而linux下呢.就需要安装一款工具了. 命令:sudo apt-g ...
- Codeforces Gym 101138 D. Strange Queries
Description 给你一下长度为 \(n\) 的序列. \(a_i=a_j\) \(l_1 \leqslant i \leqslant r_1\) \(l_2 \leqslant i \leqs ...
- 5.5---整数A转成整数B(CC150)
自己的: public static int calcCost(int A,int B){ int ans = 1; int temp = A ^ B; while(temp != 1){ if(te ...
- centos mysql 大量数据导入时1153 错误:1153 - Got a packet bigger than 'max_allowed_packet' bytes
参考:http://stackoverflow.com/questions/93128/mysql-error-1153-got-a-packet-bigger-than-max-allowed-pa ...
- 求最大公约数和小于n的所有质数
//algorithm.h enum SWAP_TYPE{MEMORY, COMPLEX}; struct SIntArray { int *pData; int num; SIntArray():p ...
- 【Networking】容器网络大观 && SDN 资料汇总
SDNLAB技术分享(十五):容器网络大观 SDNLAB君• 16-06-17 •2957 人围观 编者按:本文系SDNLAB技术分享系列,本次分享来自SDN撕X群(群主:大猫猫)群直播,我们希望 ...
- How do I get ASP.NET Web API to return JSON instead of XML using Chrome
public static class WebApiConfig { public static void Register(HttpConfiguration config) { config.Ro ...
- 第七天 面向对象进阶与socket编程
1.静态方法(用得少)(解除某个函数跟类的关联,加了静态方法后,类便不能将类的参数传给静态方法函数了) class Dog(object): def __init__(self,name): @sta ...
- [Linux]yum开启rpm包缓存
在CentOS下用yum安装,回发现在/var/cache/yum/下的base.extrs和updates下的packages下都没有发现下载的RPM 原来在/etc/yum.conf下没有设置下载 ...
- apache官网怎样下载apache HTTP Server服务器
我相信有些朋友刚用apache服务器时,都希望从官网上下载,而面对着官网上众多的项目和镜像以及目录,也许有点茫然.下面是具体步骤 第一步:打开apache官网 第二步:点击右上角Download,出现 ...