这几天在做项目的时候遇到一个问题,那就是如何做到时时监控。当时因为一些事情没有做。后来换了一个项目,关于支付系统中的对账,要做时时对账,呵呵,出来混总是要还的。今天我们就来看一个小例子来实现时时调度。
一、时时任务
1、控制类
public class timeTest {
/**
* 时时调度
* 3秒后开始,每隔1秒打印一次
*/
public static void executePerDay() {
ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
System.out.println("时时调度");
//打印当前时间
System.out.println("getTest()"+ new Date().toString());
executor.scheduleAtFixedRate(
new payTest(), //调用执行方法的类
3000, //初始化延迟3秒
1000, //每隔1秒执行一次
TimeUnit.MILLISECONDS);
}
}
2、正真执行者
public class payTest implements Runnable {
@Override
public void run() {
//打印当前时间
System.out.println("getTest()"+ new Date().toString());
}
}
3、主类
public class mainTest {
public static void main(String[] args) {
timeTest test = new timeTest();
//时时调度
test.executePerDay();
}
}
看上去很简单吧,其实也就这么简单,接下来我们做一下变形,做一个定时执行的小例子。
二、定时任务
1、控制类
public class timeTest {
/**
* 时时调度
* 3秒后开始,每隔1秒打印一次
*/
public static void executePerDay() {
ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
long oneDay = 24 * 60 * 60 * 1000;
//计算时间间隔
long initDelay = getTimeMillis("14:46:14") - System.currentTimeMillis();
//判断当天的执行时间是否已过,如果已过,需要等到第二天执行
initDelay = initDelay > 0 ? initDelay : oneDay + initDelay;
System.out.println("时时调度");
System.out.println("getTest()"+ new Date().toString());
executor.scheduleAtFixedRate(
new payTest(), //调用执行方法的类
initDelay, //初始化延迟
oneDay, //每隔多久执行一次
TimeUnit.MILLISECONDS);
}
/**
* 获取指定时间对应的毫秒数
* @param time "HH:mm:ss"
* @return
*/
private static long getTimeMillis(String time) {
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()) + " " + time);
return curDate.getTime();
} catch (Exception e) {
e.printStackTrace();
}
return 0;
}
}
总结:
这样我们通过ScheduledExecutorService 类,就实现了时时调度,至于它的运行机理,还有解析等,我会在下篇博客中给大家分享。