java简单的定时器实现

	/**
	 * 文章的定时发布。
	 */
	public static void start(){
		
		//初始化 去查询一下
		List<QtArticle> list = QtArticle.dao.find("select * from qt_article where showOrHide=1 ");
		System.out.println(list.size());
		
		if(list.size() != 0 ){
			for(int i=0;i<list.size();i++){
				String timingTime = list.get(i).getDate("timingTime").toString().substring(0, 19);
				ArticleController.map.put(list.get(i).getInt("id"), timingTime);
				CacheKit.put("usercache", "map", ArticleController.map);
	    	}
		}
		//
		
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		List<Integer> idlist =new ArrayList<Integer>();//存id
		TimerTask task = new TimerTask() {  
	        @Override  
	        public void run() {  
	            // task to run goes here  
	         //   System.out.println("Hello !!!");  
	            Map<Integer,String> map = CacheKit.get("usercache", "map");
	            if(map==null || map.size()==0){
	            	return;
	            }
	            for (Map.Entry<Integer, String> m :map.entrySet())  {  
    	          //  System.out.println(m.getKey()+"\t"+m.getValue());  
					try {
						Date dt1 = df.parse(m.getValue());
						Date now =new Date();//现在时间
						//System.out.println(dt1.getTime()+"===="+now.getTime());
						//很难相等 while(true) 可以  现在时间大于了规定时间 就显示(会有一些误差 毫秒)
						if(dt1.getTime() < now.getTime()){
							//定时数据显示
							boolean bool = QtArticle.dao.editArticleShow(m.getKey());	
							if(bool){
								idlist.add(m.getKey());
							}
						}
						
					} catch (ParseException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
	            }
	            
	            for(int i=0;i<idlist.size();i++){
	    	        map.remove(idlist.get(i));
    	        }
	        }  
	    };  
	    Timer timer = new Timer();  
	    long delay = 10*1000;//10s  第一次延迟时间
	    long intevalPeriod = 30 * 1000;  //30s 每30秒 执行一次
	    // schedules the task to be run in an interval  
	    timer.scheduleAtFixedRate(task, delay, intevalPeriod);  
	}

猜你喜欢

转载自blog.csdn.net/qq_36073929/article/details/78424539