惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
Google DeepMind News
Google DeepMind News
aimingoo的专栏
aimingoo的专栏
Microsoft Security Blog
Microsoft Security Blog
T
Tenable Blog
Security Archives - TechRepublic
Security Archives - TechRepublic
W
WeLiveSecurity
D
DataBreaches.Net
Attack and Defense Labs
Attack and Defense Labs
H
Heimdal Security Blog
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
AI
AI
P
Proofpoint News Feed
PCI Perspectives
PCI Perspectives
Schneier on Security
Schneier on Security
T
Threatpost
GbyAI
GbyAI
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
H
Help Net Security
F
Full Disclosure
T
Threat Research - Cisco Blogs
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
M
MIT News - Artificial intelligence
L
Lohrmann on Cybersecurity
Martin Fowler
Martin Fowler
博客园 - 【当耐特】
Y
Y Combinator Blog
腾讯CDC
The Hacker News
The Hacker News
博客园 - Franky
Hacker News - Newest:
Hacker News - Newest: "LLM"
博客园_首页
Simon Willison's Weblog
Simon Willison's Weblog
L
LINUX DO - 最新话题
Security Latest
Security Latest
Know Your Adversary
Know Your Adversary
Forbes - Security
Forbes - Security
Application and Cybersecurity Blog
Application and Cybersecurity Blog
S
SegmentFault 最新的问题
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
L
LangChain Blog
Vercel News
Vercel News
Cisco Talos Blog
Cisco Talos Blog
量子位
P
Proofpoint News Feed
H
Hacker News: Front Page
Help Net Security
Help Net Security
L
LINUX DO - 热门话题
Project Zero
Project Zero
C
Cisco Blogs

博客园 - 牦牛

Linux常用命令 错误:80040154 没有注册类 的问题 访问IIS网站需要输入用户名密码(非匿名登录)问题汇总 IE10、IE11 User-Agent 导致的 ASP.Net 网站无法写入Cookie 问题 端口占用问题 中国电信翼支付网关接口接入 修改Tomcat响应请求时返回的Server内容 模拟用户点击弹出新页面 Eclipse常用设置 Tomcat服务无法启动的问题 JavaScript继承的模拟实现 Windows Server 2008 小操作汇总 手机也能连VPN,再来个远程控制PC这种事你以为我会随便说么! - 牦牛 Windows下Git服务器搭建及使用过程中的一些问题 Oracle PL/SQL中的循环处理(sql for循环) CSS的display小记 博客园添加访问人数统计 IIS故障问题(Connections_Refused)分析及处理 Windows Server 2008自定义桌面
[转]Java实现定时任务的三种方法
牦牛 · 2014-08-09 · via 博客园 - 牦牛

  在应用里经常都有用到在后台跑定时任务的需求。举个例子,比如需要在服务后台跑一个定时任务来进行非实时计算,清除临时数据、文件等。在本文里,我会给大家介绍3种不同的实现方法:

  • 普通thread实现
  • TimerTask实现
  • ScheduledExecutorService实现

普通thread

这是最常见的,创建一个thread,然后让它在while循环里一直运行着,通过sleep方法来达到定时任务的效果。这样可以快速简单的实现,代码如下:

public class Task1 {
public static void main(String[] args) {
  // run in a second
  final long timeInterval = 1000;
  Runnable runnable = new Runnable() {
  public void run() {
    while (true) {
      // ------- code for task to run
      System.out.println("Hello !!");
      // ------- ends here
      try {
       Thread.sleep(timeInterval);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
      }
    }
  };
  Thread thread = new Thread(runnable);
  thread.start();
  }
}

用Timer和TimerTask

上面的实现是非常快速简便的,但它也缺少一些功能。
用Timer和TimerTask的话与上述方法相比有如下好处:

  • 当启动和去取消任务时可以控制
  • 第一次执行任务时可以指定你想要的delay时间

在实现时,Timer类可以调度任务,TimerTask则是通过在run()方法里实现具体任务。
Timer实例可以调度多任务,它是线程安全的。
当Timer的构造器被调用时,它创建了一个线程,这个线程可以用来调度任务:

import java.util.Timer;
import java.util.TimerTask;
public class Task2 {
  public static void main(String[] args) {
    TimerTask task = new TimerTask() {
      @Override
      public void run() {
        // task to run goes here
        System.out.println("Hello !!!");
      }
    };
    Timer timer = new Timer();
    long delay = 0;
    long intevalPeriod = 1 * 1000;
    // schedules the task to be run in an interval
    timer.scheduleAtFixedRate(task, delay,
                                intevalPeriod);
  } // end of main
}

ScheduledExecutorService

ScheduledExecutorService是从Java SE 5的java.util.concurrent里,做为并发工具类被引进的,这是最理想的定时任务实现方式。
相比于上两个方法,它有以下好处:

  •  相比于Timer的单线程,它是通过线程池的方式来执行任务的
  •  可以很灵活的去设定第一次执行任务delay时间
  •  提供了良好的约定,以便设定执行的时间间隔

 我们通过ScheduledExecutorService#scheduleAtFixedRate展示这个例子,通过代码里参数的控制,首次执行加了delay时间:

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class Task3 {
  public static void main(String[] args) {
    Runnable runnable = new Runnable() {
      public void run() {
        // task to run goes here
        System.out.println("Hello !!");
      }
    };
    ScheduledExecutorService service = Executors
                    .newSingleThreadScheduledExecutor();
    service.scheduleAtFixedRate(runnable, 0, 1, TimeUnit.SECONDS);
  }
}