使用jse的TimerTask实现在一天中的某个区间段定时任务

实现原理:通过定时频率判断是否在所指定的区间,还可以在所指定的区间再写一个定时器满足复杂需求

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

public class Snippet {
	public static void main(String[] args) {
		final String[] zone = "01:00-3:00".split("-");
		final String[] m = zone[0].split(":");
		final String[] m2 = zone[1].split(":");

		new Timer().schedule(new TimerTask() {
			SimpleDateFormat sFormat = new SimpleDateFormat("HH:mm");
			String str = "";

			@Override
			public void run() {
				str = sFormat.format(new Date());
				if (CheackTime(m[0], m2[0], m[1], m2[1])) {
					if (CheackIn(str, zone[0], zone[1])) {
						System.out.println("在具体区间执行了");
					}
				} else {
					System.exit(0);
				}

			}
		}, 0, 1000);
	}

	private static boolean CheackIn(String gstr, String strt1, String strt2) {
		String string1[] = strt1.split(":");
		String string2[] = strt2.split(":");
		String string3[] = gstr.split(":");
		int tgstr = Integer.parseInt(string3[0]) * 60
				+ Integer.parseInt(string3[1]);
		int tstrt1 = Integer.parseInt(string1[0]) * 60
				+ Integer.parseInt(string1[1]);
		int tstrt2 = Integer.parseInt(string2[0]) * 60
				+ Integer.parseInt(string2[1]);
		if (tgstr >= tstrt1 && tgstr <= tstrt2) {
			return true;
		} else {
			return false;
		}

	}

	private static boolean CheackTime(String h1, String h2, String m1, String m2) {
		if (Integer.parseInt(h2) < Integer.parseInt(h1)
				|| Integer.parseInt(h2) < 0 || Integer.parseInt(h1) < 0
				|| Integer.parseInt(h2) > 23 || Integer.parseInt(h1) > 23) {
			return false;
		} else if (Integer.parseInt(m2) > 60 || Integer.parseInt(m1) > 60
				|| Integer.parseInt(m2) < 0 || Integer.parseInt(m1) < 0) {
			return false;
		} else {
			return true;
		}

	}

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值