• 笔记——Java定时任务Timer入门


    import java.text.ParseException;
    import java.text.SimpleDateFormat;
    import java.util.Timer;
    
    public class TimerManager {
    	public static int count= 0 ;
    	private DTimerTask task;
    	public TimerManager() throws ParseException {
    		final SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); //时间格式化
    		task=new DTimerTask();		//创建一个TimerTask子类 在子类的run方法中执行操作
    		Timer timer=new Timer();
    		//三个参数分别代表:定时任务子类、开始时间、间隔时间(毫秒)
    		timer.schedule(task, sdf.parse("2018-01-26 11:23:20"),5*1000); // 5*1000 代表5秒
    		//timer.scheduleAtFixedRate(d, sdf.parse("2018-01-26 09:12:20"),20*1000);
    	}
    	public static void main(String[] args) throws ParseException {
    		TimerManager timer = new TimerManager();
    		System.out.println("启动TimerManager完成。。。。");
    		while(true){
    			if(count>3) {
    				timer.task.cancel();
    				System.out.println("timer任务清除。。。。。");
    				System.exit(1);
    			}else {
    				System.out.println("时机未到。。。。。");
    				try {
    					Thread.sleep(5*1000);
    				} catch (InterruptedException e) {
    					e.printStackTrace();
    				}
    			}
    		}
    	}
    }
    import java.util.Date;
    import java.util.TimerTask;
    
    public class DTimerTask extends TimerTask {
    
    	@Override
    	public void run() {
    		TimerManager.count++;
    		System.out.println(new Date());
    	}
    
    }

    当开始时间为已经过去的时间时:scheduleAtFixedRate方法会把遗漏的操作都补上,而schedule不会,schedule会直接以当前时间为开始时间。



  • 相关阅读:
    Android官方架构组件介绍之ViewModel
    Android官方架构组件介绍之LiveData
    Android官方架构组件介绍之LifeCycle
    Android N 通知概览及example
    Project和Task
    hello gradle
    写出gradle风格的groovy代码
    Groovy中的面向对象
    tcp_tw_recycle和tcp_timestamps的一些知识(转)
    Xtrabackup 热备
  • 原文地址:https://www.cnblogs.com/dingzuoheng/p/12805081.html
Copyright © 2020-2023  润新知