定时器经常在项目中用到,定制执行某些操作,比如爬虫就需要定时加载种子等操作,之前一直用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);
}