使用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 ...
随机推荐
- jquery的change():下拉框值改变时触发
<script src="jquery.min.js" type="text/javascript"></script> <scr ...
- CCF 模拟D 动态规划
http://115.28.138.223:81/view.page?opid=4 这道题写的我醉醉的,想建一棵指定深度的树最后统计满足条件的个数 居然没去考虑这样必然超时!!!代码写的也是醉了,把没 ...
- BZOJ 3827: [Poi2014]Around the world
Sol 并查集. 一个点所能到达的最远是单调不降的.然后将链延长到两倍,预处理出每个点到达的最远点,然后倒着计算深度. 再然后一直跳,跳到>=x+n的点,因为跳到的点都能到最终的点,并且不影响后 ...
- 1.3---字符串重新排列后是否能够变成另一个字符串(CC150)
import java.util.*; public class Same { public boolean checkSam(String str1, String str2) { // write ...
- 借助 SublimeLinter 编写高质量的 JavaScript & CSS 代码
SublimeLinter 是前端编码利器——Sublime Text 的一款插件,用于高亮提示用户编写的代码中存在的不规范和错误的写法,支持 JavaScript.CSS.HTML.Java.PHP ...
- 【Java】Java 深入探讨 单例模式的实现
在GoF的23种设计模式中,单例模式是比较简单的一种.然而,有时候越是简单的东西越容易出现问题.下面就单例设计模式详细的探讨一下. 所谓单例模式,简单来说,就是在整个应用中保证只有一个类的实例存在 ...
- Excel导出的几种方式
1.html 前台html与js代码(文件:ExportExcelByHtml.aspx): <html xmlns="http://www.w3.org/1999/xhtml&quo ...
- Android studio教程
Android studio教程: http://jingyan.baidu.com/season/44062
- Binary Tree Vertical Order Traversal
Given a binary tree, return the vertical order traversal of its nodes' values. (ie, from top to bott ...
- C# 读写ini文件
1.添加引用 using System.IO; using System.Runtime.InteropServices; 2.声明API函数 #region API函数声明 [DllImport(& ...