java timer定时器简单实用

1、指定延迟时间+循环执行操作

public class TimerTest {
	String path = "C:\\Users\\Administrator\\Desktop\\";
	Timer timer;
	public TimerTest(int time){
		timer = new Timer();
		timer.schedule(new timeTaskTest() , time*1000, 2000);//timer.schedule(执行的方法,延迟多久执行(ms))
	}
	
	class timeTaskTest extends TimerTask{
		@Override
		public void run() {
			File dir = new File(path);
			File[] files = dir.listFiles();
			if (files != null) {
				for (File file : files) {
					if (!file.isDirectory()) {
						String fileName = file.getName();
						if (fileName.equals("false.txt")) {
							System.out.println("文件名:" + fileName + ",还存在!!!");
						}else if (fileName.equals("true.txt")) {
							System.out.println("文件false.txt被修改!!!");
							timer.cancel();
							System.out.println("取消定时任务!!!");
						}
					}
				}
			}	
		}
	}
	
	public static void main(String[] args) {
		System.out.println("timer begin...");
		new TimerTest(3);
	}
}

2、指定时间执行操作

public class TimerTest1 {
	Timer timer;

	public TimerTest1() {
		Date date = getTime();
		System.out.println("指定时间:" + date);
		timer = new Timer();
		timer.schedule(new TimerTaskTest2(), date);// timer.schedule(执行的方法,要执行的时间)
	}

	public Date getTime() {
		Calendar calendar = Calendar.getInstance();
		calendar.set(Calendar.HOUR, 11);
		calendar.set(Calendar.MINUTE, 33);
		calendar.set(Calendar.SECOND, 00);
		Date date = calendar.getTime();
		return date;
	}

	class TimerTaskTest2 extends TimerTask {

		@Override
		public void run() {
			// TODO Auto-generated method stub
			System.out.println("指定时间执行线程任务...");
		}
	}

	public static void main(String[] args) {
		new TimerTest1();
	}

}

 

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

粥截轮

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值