java内部定时任务用的类:import java.util.Timer,import java.util.TimerTask;。、
在执行一些简单的延时任务时,使用java内部的定时任务比quartz要简单,用起来方便快捷,当然,如果需要比较复杂的定时任务,比如动态管理、比较复杂的指定时间、多任务执行等,还是需要用上quartz,此处就Java内部定时任务的应用作简要介绍,不作深入分析。
场景介绍:
在web的service执行某一数据库操作后,需要指定时间后对指定的实体类数据进行操作。
思路:
service执行操作的最后,建立一个定时任务,并把实体类的id传给定时任务类的方法,用以在执行时获取该实体类(注:不能将实体类的对象传进去,执行时会报空指针错误,因为此时实体类对象已经为null)。
下面上代码:
首先是model层的实体类:
package com.xmty.testmd5;
import java.util.Date;
/**
* 被定时任务操作的实体类
*
* @author snow
*
*/
public class ExecuteModel {
// 实体类id
String id;
// 执行时间
Date executeTime;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public Date getExecuteTime() {
return executeTime;
}
public void setExecuteTime(Date executeTime) {
this.executeTime = executeTime;
}
}
下面是调用任务的service层类:
package com.xmty.testmd5;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import com.xmty.util.MyTimeTask;
/**
* 创建定时任务的类
* 相当于service层的类
* @author snow
*
*/
public class TestTime {
public static void main(String[] args) {
ExecuteModel model = new ExecuteModel();
String id = "aaa";
Date executeTime = null;
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
executeTime = format.parse("2017-03-11 21:34:50");
} catch (ParseException e) {
e.printStackTrace();
}
model.setId(id);
model.setExecuteTime(executeTime);
//建立一个定时任务
new MyTimeTask().noticeLost(id, executeTime);
}
}
package com.xmty.util;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
import com.xmty.testmd5.ExecuteModel;
/**
* 执行定时任务的类
* @author snow
*
*/
public class MyTimeTask {
/**
* dao层访问接口
* 可以根据executeModel的id通过dao从数据库中取出
* 进行数据库数据的定时操作
*/
/*IDao dao = (IDao) SpringApplicationContextHolder
.getSpringBean("dao");*/
//定时对象(java工具类)
Timer timer = new Timer();
//定时任务内部类
class Item extends TimerTask{
//执行时间
Date executeTime;
//被操作实体类id
//用来从数据库取出实体类
String id;
//构造方法
Item(String id, Date executeTime){
this.id = id;
this.executeTime = executeTime;
}
public void run() {
try {
operate(id, executeTime);
} catch (ParseException e) {
e.printStackTrace();
}
}
}
//定时任务执行的类,执行时notice已经为null,传递
public void operate(String id, Date executeTime) throws ParseException{
// ExecuteModel model = dao.getById(id);
// if (executeTime.getTime() == model.getExecuteTime().getTime()) {
System.out.println("执行了定时方法 " + executeTime);
//若只执行一次,则调用timer.cancel()取消定时任务
timer.cancel();
// }
}
public void noticeLost(String id, Date executeTime){
//创建定时任务
Item item = new Item(id, executeTime);
//启动定时任务
timer.schedule(item,executeTime);
}
}
测试时执行结果如下图:
由于在执行后调用了timer.cancel()方法,取消了当前的定时任务,所以程序自动结束,实现了一次性定时任务的功能。
注:一个timer对应一个单独的线程,这种定时任务是线程安全的,定时任务不需要了,最好调用timer.cancel()方法将线程结束。
2911

被折叠的 条评论
为什么被折叠?



