java_Timer_schedule jdk自带定时器
定时器经常在项目中用到,定制执行某些操作,比如爬虫就需要定时加载种子等操作,之前一直用spring的定制器
近期做项目发现,jdk有很简单的提供 代码如下
1 /* 2 * Copyright (c) 2014-2024 . All Rights Reserved. 3 * 4 * This software is the confidential and proprietary information of 5 * LoongTao. You shall not disclose such Confidential Information 6 * and shall use it only in accordance with the terms of the agreements 7 * you entered into with LoongTao. 8 * 9 */ 10 package com.loongtao.dmscrawler.temp; 11 12 import java.util.Timer; 13 import java.util.TimerTask; 14 15 /** 16 * @declare:测试定时器 <br> 17 * @author: cphmvp 18 * @version: 1.0 19 * @date: 2014-3-14上午11:21:36 20 */ 21 public class TimeTest { 22 public static void main(String[] args) { 23 System.out.println("start"); 24 new Timer().schedule(new TestTask(), 0, 1000 * 60 * 60); 25 System.out.println("end"); 26 27 } 28 29 static class TestTask extends TimerTask { 30 TestTask() { 31 // 空构造器 32 } 33 34 @Override 35 public void run() { 36 System.out.println(1); 37 } 38 39 } 40 }
jdk源码参考 很容易看懂的 ,不解释
1 * @param task task to be scheduled. 2 * @param delay delay in milliseconds before task is to be executed. 3 * @param period time in milliseconds between successive task executions. 4 * @throws IllegalArgumentException if <tt>delay</tt> is negative, or 5 * <tt>delay + System.currentTimeMillis()</tt> is negative. 6 * @throws IllegalStateException if task was already scheduled or 7 * cancelled, timer was cancelled, or timer thread terminated. 8 */ 9 public void schedule(TimerTask task, long delay, long period) { 10 if (delay < 0) 11 throw new IllegalArgumentException("Negative delay."); 12 if (period <= 0) 13 throw new IllegalArgumentException("Non-positive period."); 14 sched(task, System.currentTimeMillis()+delay, -period); 15 }
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。