java实现自制定时器

java实现自制定时器。
最近因为项目需求现在想封装一个定时器。
具体需要实现的功能为。
(1)直接调用一个方法就可以启动定时器。
(2)这个定时器支持设置定时时长,设置定时循环次数和定时的间隔时长。
(3)支持多线程调用这个定时器对象。当时间到了通过回调方法启动事件。


下面是实现代码:


public class TimerTaskTool {


/**

* @param loopCount
*            //循环次数
* @param longTime
*            //距离第一次执行时长(单位:分钟)
* @param longTime2
*            //循环间隔时长(单位:分钟)
* @param taskInter
*/
public static void addTimerTask(final Integer loopCount,final Integer longTime, final Integer longTime2, final TaskInter taskInter) {
new Thread() {
public void run() {
System.out.println("这个定时任务在添加到定时器中"+longTime+"秒后开始以"+longTime2
+"秒的间隔循环执行"+loopCount+"次(-1次为无限次)");
try {
Thread.sleep(longTime * 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}


int i = 0;
while (i < loopCount || loopCount<0) {
taskInter.executeTask();
if(loopCount>=1)
i++;
if(i!=loopCount)
try {
Thread.sleep(longTime2 * 1000 );
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}.start();
}
}










import java.io.IOException;
public class Test{
public static void main(String[] args) {
TimerTask1.addTimerTask(5, 1, 2, new TaskInter() {
public void executeTask() {
try {
Runtime.getRuntime()
.exec("E:\\Program Files (x86)\\Tencent\\QQ\\Bin\\QQScLauncher.exe");//启动qq
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// System.out.println("定时任务A执行一次");
}
});
new Thread() {
public void run() {
TimerTask1.addTimerTask(5, 2, 3, new TaskInter() {
public void executeTask() {
try {
Runtime.getRuntime()
.exec("C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe");//启动浏览器
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// System.out.println("定时任务B执行一次");
}
});
};
}.start();


}
}



猜你喜欢

转载自blog.csdn.net/qq_29428215/article/details/75267857
今日推荐