java项⽬设置定时执⾏任务的⼏种⽅式
最近在做项⽬的中过程中有⼀个需求:将⼀个公告在⼀个特定时间发送。于是上⽹查询定时执⾏任务,上⾯有三种定时执⾏任务的⽅式。分别是1.普通thread实现
2.TimerTask实现
3.ScheduledExecutorService实现。下⾯⼀⼀介绍,
public class Task1 {
public static void main(String[] args) {
// run in a second
final long timeInterval = 1000;
Runnable runnable = new Runnable() {
public void run() {
while (true) {
// ------- code for task to run
System.out.println("Hello !!");
// ------- ends here
try {
Thread.sleep(timeInterval);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
Thread thread = new Thread(runnable);
thread.start();
}
}
⼆、⽤Timer和TimerTask
上⾯的实现是⾮常快速简便的,但它也缺少⼀些功能。
⽤Timer和TimerTask的话与上述⽅法相⽐有如下好处:
1.当启动和去取消任务时可以控制
2.第⼀次执⾏任务时可以指定你想要的delay时间
在实现时,Timer类可以调度任务,TimerTask则是通过在run()⽅法⾥实现具体任务。
Timer实例可以调度多任务,它是线程安全的。
当Timer的构造器被调⽤时,它创建了⼀个线程,这个线程可以⽤来调度任务。
st;
ParseException;
SimpleDateFormat;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
/**
* Timer:可以调度任务
* TimeTask:在run()⽅法中实现具体的任务
* @author duanhongyan
*
*/
public class TestTask {
public static void main(String[] args) {
TimerTask task = new TimerTask() {
@Override
public void run() {
// task to run goes here
System.out.println("Hello ");
}
};
Timer timer = new Timer();
long delay = 0;
long intevalPeriod = 1 * 1000;
// schedules the task to be run in an interval
timer.scheduleAtFixedRate(task, delay,
intevalPeriod);
}
}
三、ScheduledExecutorService
ScheduledExecutorService是从Java SE 5的urrent⾥,做为并发⼯具类被引进的,这是最理想的定时任务实现⽅式。相⽐于上两个⽅法,它有以下好处:
1.相⽐于Timer的单线程,它是通过线程池的⽅式来执⾏任务的
2.可以很灵活的去设定第⼀次执⾏任务delay时间
3.提供了良好的约定,以便设定执⾏的时间间隔
下⾯是实现代码,我们通过ScheduledExecutorService#scheduleAtFixedRate展⽰这个例⼦,通过代码⾥参数的控制,⾸次执⾏加了delay时间。
import urrent.Executors;
import urrent.ScheduledExecutorService;
import urrent.TimeUnit;
public class Task3 {
单例模式的几种实现方式
public static void main(String[] args) {
Runnable runnable = new Runnable() {
public void run() {
// task to run goes here
System.out.println("Hello !!");
}
};
ScheduledExecutorService service = Executors
.newSingleThreadScheduledExecutor();
service.scheduleAtFixedRate(runnable, 0, 1, TimeUnit.SECONDS);
}
}
针对这种任务只是发送⼀⼀次的任务我是采⽤了第⼆种较为简单的⽅式,直接⽤Timer去执⾏⼀个定时任务,执⾏完成⼀次之后⾃⼰断开,这⾥采⽤的是单例的模式,不会每次请求Timer的时候都去新增⼀个Timer()对象,是采⽤spirng注⼊的⽅式:
然后在NoticeRestImpl中调⽤timer服务
然后这样就可以使得Timer只是新建⼀个对象,然后通过这⼀个Timer(任务调度)来管理多个TimerTask(任务),单例模式的好处就在于此,对于那种每请求⼀次都要新建⼀个TIimer对象,然后如果有多个TimeTask任务就要⽤多个Timer来管理,不太合理
然后调⽤这个⽅法就是通过实现Timer的run()⽅法来多次执⾏指定的任务
还有⼀种情况:每隔⼀段时间对⼀个⽂件夹进⾏扫描,
配置如下
这是在我的服务⾥⾯配置的,具体的服务如下
dt.st.impl;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
DateFormat;
SimpleDateFormat;
import java.util.Date;
import org.json.JSONObject;
dt.license.ity.CenterIndexData;
dt.license.ity.LicenseStatus;
dt.st.util.ConfigUtil;
dt.st.util.PDFXmlUtil;
dt.license.manage.service.CenterDataService;
public class ThreadGetpdf extends Thread {
private CenterDataService centerDataService;
public void setCenterDataService(CenterDataService centerDataService) {  DataService = centerDataService;
}
private Long delay;
public void setDelay(Long delay) {
this.delay = delay;
}
private String path = new ConfigUtil().getPdfPath();
public void run() {
// logger.debug("扫描⽂件夹线程启动!");
// 临时:while(true)不可控,要修改,还没想好怎么改
boolean tag = true;
while (true) {
// logger.debug("开始运⾏。");
try {
File file = new File(path);
File[] files = file.listFiles();
if (files.length == 0) {
tag = false;
}
if (files != null) {
for (File f : files) {
/
/ 将xml都转换为⼀个javabean对象
String pdfPath = f.getPath();
new PDFXmlUtil();
// 解析pdf⽂件
JSONObject param = new JSONObject();
try {
String pdf = PDFXml(pdfPath);
param = new JSONObject(pdf)
.optJSONObject("businessData");
} catch (Exception e) {
// e.printStackTrace();
}
CenterIndexData entity = new CenterIndexData();
entity.setHolder(param.optString("holder"));
entity.setSerNum(param.optString("serNum"));
entity.setLicAttrs(param.optString("licAttrs"));
entity.setLicenseStatus((LicenseStatus.valueOf(param
.optString("licenseStatus"))));
entity.setLicName(param.optString("licName"));
entity.setLicType(param.optString("licType"));
entity.setStamper(param.optString("stamper"));
String staDate = param.optString("staDate");
DateFormat fmt =new SimpleDateFormat("yyyy-MM-dd");
Date date = null;
try {
date = fmt.parse(staDate);
} catch (Exception e) {
e.printStackTrace();
}
entity.setStaDate(date);
entity.setIssuer(param.optString("issuer"));
entity.setProvideOrg(param.optString("provideOrg"));
String pdfPathcopy = new ConfigUtil().getPdfPathcopy()
+ f.getName();
System.out.println(pdfPathcopy);
entity.setPdfPath(pdfPathcopy);
String toFilePath = new ConfigUtil().getPdfPathcopy();
getFile2(f, toFilePath);
centerDataService.add(entity);
}
}
} catch (Exception e1) {
// e1.printStackTrace();
continue;
}
try {
synchronized (this) {
wait(delay);
}
} catch (InterruptedException e) {
e.printStackTrace();
continue;
}
}
}
public static void main(String[] args) {
String pdfPath="D:/lic_repo/pdf/00177~00067~license~车艾丝凡带⼿机过来撒娇~4400001001030002~车艾丝凡带⼿机过来撒娇.pdf";  String pdf = PDFXml(pdfPath);
System.out.println(pdf);
}
/**
* 将某⽂件夹下⾯的⽂件移动到另⼀个⽂件夹
*
* @param dir
*            要移动的⽂件夹名

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。