zoukankan      html  css  js  c++  java
  • 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     }
  • 相关阅读:
    浏览器缓存机制
    es6笔记(6) Iterator 和 for...of循环
    es6笔记(3.1)三个点的“...”的作用
    es6笔记(5)Map数据结构
    es6笔记(4) Set数据结构
    SpringBoot事件监听
    SpringBoot入门
    五大常用算法之三贪心算法
    五种常用算法之二:动态规划算法
    五大常用算法之一:分治算法
  • 原文地址:https://www.cnblogs.com/cphmvp/p/3600516.html
Copyright © 2011-2022 走看看