基于时间段的Timer定时器执行任务

本文介绍了一个使用 Java Timer API 实现的任务调度程序。该程序能够根据不同的参数设置,在指定时间或周期性地执行任务。文章详细解释了如何通过四种不同模式来配置任务执行逻辑,并提供了一个具体的实现案例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package com.timerTools;

import java.util.Calendar;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

public class TestTimer {  
	Timer timer = new Timer();  

    //定时器,执行任务测试
    public static void main(String[] args) {  
    	new TestTimer().executeTask(3,null,1000,1000); 
    } 
    
	/**
	 * 定时器任务制定,执行
	 * @param tag: 0.在指定的时间里,执行指定的任务;
	 * 			   1.在指定的时间里,按照指定的延迟,重复执行指定任务;
	 *             2.从指定的延迟后,执行指定任务;
	 *             3.从指定的延迟后,按照指定的延迟,重复执行指定的任务。
	 *             
	 * @param mydate:指定的执行时间。只有在tag等于0、1才需要指定。            
	 * @param delay: 延迟执行时间,毫秒数。只有在tag等于1、3才需要指定。
	 * @param period:间隔执行时间,毫秒数。只有在tag等于4才需要指定。
	 */
    public void executeTask(int tag, Date mydate,long delay, long period) {  
    	if(tag == 0){
    		timer.schedule(new DefineTimerTask(), mydate);
    	}else if(tag == 1){
    		timer.schedule(new DefineTimerTask(), mydate, period);
    	}else if(tag == 2){
    		timer.schedule(new DefineTimerTask(),delay);
    	}else if(tag == 3){
    		timer.schedule(new DefineTimerTask(),delay,period);
    	}else{
    		System.out.println("Error:输入的定时器参数无效!");
    	}  
    } 
    
	/** 
	 * 执行的定时器任务
	 */  
    private class DefineTimerTask extends TimerTask {  
        //执行的次数  
    	boolean isTimes = true;  
        
        public void run() {  
        	isTimes = isTimes();
        	if(isTimes){
        		System.out.println("执行定时器任务开始 :" + System.currentTimeMillis());  
        	}else{
        		System.out.println("----------------- 执行定时器任务结束:" + System.currentTimeMillis());  
        		timer.cancel(); 
        	}
        }  
    }  
    
    
    
    
    //是否满足时间周期
    public static boolean isTimes(){
    	boolean isTimes = false;
    	String newWeek = "2";
    	String times = "17:00-17:10,17:10-17:15,17:24-17:25,17:25-17:26"; //
    	
    	String[] newWeeks = newWeek.split(",");
    	String[] timess   =  times.split(",");

    	Calendar   cal   =   Calendar.getInstance(); 
    	cal.setTime(new Date()); 
    	
    	int week = cal.get(Calendar.DAY_OF_WEEK);
    	if(week == 1){
    		week = 7;
    	}else{
    		week = week-1;
    	}
    	
        try {
        	for(int i=0;i<newWeeks.length;i++){
        		//是否是指定的周期
        		if(Integer.parseInt(newWeeks[i]) == week){
        			for(int j=0;j<timess.length;j++){
        				//是否是指定的时间段
        				if(isInDates(timess[j])){
        					System.out.println("----------------- 执行定时器任务时间:[" +timess[j]+"]");  
        					return true;
        				}
        			}
        		}
        	}
		} catch (Exception e) {}
		
		return isTimes;
    }
    
    //比较两个时间是否存在交集
     public static boolean isInDates(String times){   
        Date dt = new Date();
        int strDateH = dt.getHours();  
        int strDateM = dt.getMinutes();  
          
        int strDateBeginH = Integer.parseInt(times.split("-")[0].split(":")[0]);  
        int strDateBeginM = Integer.parseInt(times.split("-")[0].split(":")[1]);  
          
        int strDateEndH = Integer.parseInt(times.split("-")[1].split(":")[0]);  
        int strDateEndM = Integer.parseInt(times.split("-")[1].split(":")[1]);  
        
        if((strDateH>=strDateBeginH && strDateH<=strDateEndH)){  
        	if(strDateH>strDateBeginH && strDateH<strDateEndH){  
                return true;  
            }else if(strDateH==strDateBeginH && strDateM>strDateBeginM && strDateH<strDateEndH){  
                return true;  
            }else if(strDateH==strDateBeginH && strDateM==strDateBeginM && strDateH<strDateEndH){  
                return true;  
            }else if(strDateH==strDateBeginH && strDateM==strDateBeginM && strDateH<strDateEndH){  
                return true;  
            }else if(strDateH==strDateBeginH && strDateH==strDateEndH && strDateM<strDateEndM){  
                return true;  
            }else if(strDateH>strDateBeginH && strDateH==strDateEndH && strDateM<strDateEndM){  
                return true;  
            }else if(strDateH>strDateBeginH && strDateH==strDateEndH && strDateM==strDateEndM ){  
                return true;  
            }else if(strDateH>strDateBeginH && strDateH==strDateEndH && strDateM==strDateEndM){  
                return true;  
            }else{  
                return false;  
            }  
        }else{  
            return false;  
        }  
    }  
    
}  

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值