您的位置:首页 > 编程语言 > Java开发

java_Timer_schedule jdk自带定时器

2014-03-14 14:29 225 查看
定时器经常在项目中用到,定制执行某些操作,比如爬虫就需要定时加载种子等操作,之前一直用spring的定制器
近期做项目发现,jdk有很简单的提供   代码如下

1 /*
* Copyright (c) 2014-2024 . All Rights Reserved.
*
* This software is the confidential and proprietary information of
* LoongTao. You shall not disclose such Confidential Information
* and shall use it only in accordance with the terms of the agreements
* you entered into with LoongTao.
*
*/
package com.loongtao.dmscrawler.temp;

import java.util.Timer;
import java.util.TimerTask;

/**
* @declare:测试定时器 <br>
* @author: cphmvp
* @version: 1.0
* @date: 2014-3-14上午11:21:36
*/
public class TimeTest {
public static void main(String[] args) {
System.out.println("start");
new Timer().schedule(new TestTask(), 0, 1000 * 60 * 60);
System.out.println("end");

}

static class TestTask extends TimerTask {
TestTask() {
// 空构造器
}

@Override
public void run() {
System.out.println(1);
}

}
}

jdk源码参考 很容易看懂的 ,不解释


* @param task   task to be scheduled.
* @param delay  delay in milliseconds before task is to be executed.
* @param period time in milliseconds between successive task executions.
* @throws IllegalArgumentException if <tt>delay</tt> is negative, or
*         <tt>delay + System.currentTimeMillis()</tt> is negative.
* @throws IllegalStateException if task was already scheduled or
*         cancelled, timer was cancelled, or timer thread terminated.
*/
public void schedule(TimerTask task, long delay, long period) {
if (delay < 0)
throw new IllegalArgumentException("Negative delay.");
if (period <= 0)
throw new IllegalArgumentException("Non-positive period.");
sched(task, System.currentTimeMillis()+delay, -period);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: