使用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搭建一个FTP服务器
1.安装vsftp 2.配置vsftpd.conf, vim /etc/vsftpd.conf 下面说说里面比较重要的选项 1 anonymous_enable=NO #不允许匿名用户 2 3 loc ...
- php DI实现实例:
<?php //DI 主要运用IoC用于解决 依赖文件共享(无需每一个依赖都手动注册) //管理应用程序中的『全局』对象(包括实例化.处理依赖关系). //可以延时加载对象(仅用到时才创建对象) ...
- 获取客户端IP
function getIP(){ $ip = ""; if (getenv("HTTP_CLIENT_IP") && strcasecmp(g ...
- Mysql5.7版本编译安装及配置
配置yum安装方式 1.配置本地yum源 vim /etc/yum.repos.d/rhel-source.repo [rhel-source] name=Red Hat Enterprise Lin ...
- sublime-text3设置浏览器预览html
选择:Tools - Build System - New Build Syatem... 或者:工具 - 编译系统 - 新编译系统 然后粘贴代码 { "cmd": [" ...
- WPF 中更新界面信息
1.Dispatcher.BeginInvoke int ii = 0; new Thread(new ParameterizedThreadStart((i) => { while (true ...
- 【leetcode】Dungeon Game
Dungeon Game The demons had captured the princess (P) and imprisoned her in the bottom-right corner ...
- Wince常见操作
1.获取本地代码启动路径 //在代码启动路径下存在 Files 文件夹 Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName(). ...
- ios 在storyboard 和 xib中,显示自定义view的预览效果
发现FSCalendar这个控件能在xib中显示预览效果,是怎么实现的呢?其中涉及的知识又有哪些? 主要就是IBInspectable 和 IB_DESIGNABLE 先看 IBInspectable ...
- Qt 对话框显示控制按钮
在对话框窗体构造函数加入 SystemDialog::SystemDialog(QWidget *parent) : QDialog(parent), ui(new Ui::SystemDialog) ...