Java定时器

本文介绍了Java中实现定时任务的几种方法,包括线程sleep、ScheduledExecutorService的scheduleAtFixedRate、定时每天凌晨执行任务,以及Timer的使用。同时对比了scheduleAtFixedRate和scheduleWithFixedDelay的区别。

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

1、使用线程睡眠方法控制,每间隔2000毫秒执行一次

final long time=2000;//2秒一次
	
	 Runnable runnable=new Runnable() {
	 
		@Override
		public void run() {
			while(true){
				System.out.println("Hello World");
				try {
					Thread.sleep(time);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	};
	Thread thread=new Thread(runnable);
	thread.start();

2、ScheduledExecutorService中scheduleAtFixedRate方法控制,间隔执行

	Runnable runnable=new Runnable() {
		
		@Override
		public void run() {
			System.out.println("Hello World");
			
		}
	};
	ScheduledExecutorService sExecutorService=Executors.newSingleThreadScheduledExecutor();
	//public ScheduledFuture<?> scheduleAtFixedRate(Runnable command,long initialDelay,long period,TimeUnit unit);
	//command:执行线程
	//initialDelay:初始化延时
	//period:两次开始执行最小间隔时间
	//unit:计时单位
	sExecutorService.scheduleAtFixedRate(runnable, 10, 1, TimeUnit.SECONDS);//间隔十秒钟后执行,第一次之后1秒执行一次
	

3、ScheduledExecutorService实现每天凌晨执行方法

	 ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);  
	    long oneDay = 24 * 60 * 60 * 1000;  
	    long initDelay  = getTimeMillis("24:00:00") - System.currentTimeMillis();//System.currentTimeMillis()获取系统当前时间
	    initDelay = initDelay > 0 ? initDelay : oneDay + initDelay;  
	  
	    executor.scheduleAtFixedRate(  
	            new Runnable() {
			 @Override
			 public void run() {
                              System.out.println("此时执行方法");						
			 }
		    },  
	            initDelay,  
	            oneDay,  
	            TimeUnit.MILLISECONDS);  
}

private static long getTimeMillis(String string) {
	try {  
        DateFormat dateFormat = new SimpleDateFormat("yy-MM-dd HH:mm:ss");  
        DateFormat dayFormat = new SimpleDateFormat("yy-MM-dd");  
        Date curDate = dateFormat.parse(dayFormat.format(new Date()) + " " + string);  
        return curDate.getTime();  
    } catch (ParseException e) {  
        e.printStackTrace();  
    }  
	return 0;
}

4、Timer实现定时执行任务

public class TimerManager {

    public static void main(String[] args) {  
        new TimerManager();    
    }  
  
    //时间间隔(一天)  
    private static final long PERIOD_DAY = 24 * 60 * 60 * 1000;  
    public TimerManager() {  
        Calendar calendar = Calendar.getInstance();  
        calendar.set(Calendar.HOUR_OF_DAY, 24); //时  
        calendar.set(Calendar.MINUTE,20);//分
        calendar.set(Calendar.SECOND,00);//秒  
//      int year = calendar.get(Calendar.YEAR);
//	    int month = calendar.get(Calendar.MONTH);
//	    int day =calendar.get(Calendar.DAY_OF_MONTH);//每天
//      calendar.set(year, month,day,15,31,00);
        Date date=calendar.getTime(); //第一次执行定时任务的时间  
        //如果第一次执行定时任务的时间 小于当前的时间  
        //此时要在 第一次执行定时任务的时间加一天,以便此任务在下个时间点执行。如果不加一天,任务会立即执行。  
        if (date.before(new Date())) {  
            date = this.addDay(date, 1);  
        }  
        Timer timer = new Timer();  
        Task task = new Task();  
        //安排指定的任务在指定的时间开始进行重复的固定延迟执行。  
        timer.schedule(task,date,PERIOD_DAY);    
    }  
    // 增加或减少天数  
    public Date addDay(Date date, int num) {  
        Calendar startDT = Calendar.getInstance();  
        startDT.setTime(date);  
        startDT.add(Calendar.DAY_OF_MONTH, num);  
        return startDT.getTime();  
    }  
}
public class Task extends TimerTask{

	@Override
	public void run() {
		System.out.println("每天定时执行此任务");
		
	}

}

5、scheduleAtFixedRate和scheduleWithFixedDelay

 //(1)创建并执行一个启用的周期性动作
	//	在给定的初始延迟之后,以及随后的给定
	//	*时期;这是在之后开始执行的
	//	@code initial延时,然后@code initial延时+句点,然后
	//	@code initial延时+2周期,等等。
	//	如果任务的执行
	//	遇到异常,随后的执行被抑制。
	//	否则,任务只会通过取消或取消
	//	遗嘱执行人的终止。如果执行这个任务
	//	花费的时间比它的周期长,然后是随后的执行
	//	可能开始晚,但不会同时执行。
	//	*
	//	@param命令执行任务
	//	@param初始化延迟第一次执行的时间
	//	@param周期是连续执行的周期
	//	@param单元初始延迟和周期参数的时间单元
	//	@返回一个计划的未来,表示等待完成
	//	这个任务,以及它的@code get()方法将会抛出一个
	//	*例外在取消
	//	如果任务不能被拒绝,那么就拒绝了。
	//	*安排执行
	//	如果命令为空,则抛出NullPointerException
	//	如果周期小于或等于零,则抛出非法的论证异常
	ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);  
        executor.scheduleAtFixedRate(  
            new Runnable() {
				
				@Override
				public void run() {
					System.out.println("执行此方法");
				}
			},  
            0,  
            1000,  
            TimeUnit.MILLISECONDS);  
	
	//(2)创建并执行一个启用的周期性动作
	//    在给定的初始延迟之后,以及随后的
	//    在终止一个执行和
	//    下一个开始。如果任务的执行
	//    遇到异常,随后的执行被抑制。
	//    创建并执行一个启用的周期性动作
	//    在给定的初始延迟之后,以及随后的
	//    在终止一个执行和
	//    下一个开始。如果任务的执行
	//    遇到异常,随后的执行被抑制。
	//    否则,任务只会通过取消或取消
	//    遗嘱执行人的终止。
	//    *
	//    @param命令执行任务
	//    @param初始化延迟第一次执行的时间
	//    @param延迟了一个终止之间的延迟
	//    执行和下一站的开始
	//    @param单元初始延迟和延迟参数的时间单元
	//    @返回一个计划的未来,表示等待完成
	//    这个任务,以及它的@code get()方法将会抛出一个
	//    *例外在取消
	//    如果任务不能被拒绝,那么就拒绝了。
	//    *安排执行
	//    如果命令为空,则抛出NullPointerException
	//    如果延迟小于或等于零,则抛出非法的争辩异常
	  ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);  
	    executor.scheduleWithFixedDelay(  
	            new Runnable() {
					
					@Override
					public void run() {
						System.out.println("执行此方法");
					}
				}, 
	            0,  
	            1000,  
	            TimeUnit.MILLISECONDS); 

 

 

 

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值