package search;
import java.util.Date;
//定时任务类
public class SchTask implements Runnable{
//定时时间间隔
private long timeout;
//任务运行状态
private boolean isRunning;
//上一次运行时间
private Date preTime;
//交易码
private String tradeCode;
//服务名
private String serviceName;
@Override
public void run() {
preTime = new Date();
try{
//调用具体业务逻辑
PubUtil.callServie(tradeCode,serviceName);
}finally{
isRunning = false;
}
}
public boolean isTrue(){
Date localDate = new Date();
long l = (localDate.getTime()-preTime.getTime());
return l>=timeout;
}
public long getTimeout() {
return timeout;
}
public void setTimeout(long timeout) {
this.timeout = timeout;
}
public boolean isRunning() {
return isRunning;
}
public void setRunning(boolean isRunning) {
this.isRunning = isRunning;
}
public Date getPreTime() {
return preTime;
}
public void setPreTime(Date preTime) {
this.preTime = preTime;
}
public String getTradeCode() {
return tradeCode;
}
public void setTradeCode(String tradeCode) {
this.tradeCode = tradeCode;
}
public String getServiceName() {
return serviceName;
}
public void setServiceName(String serviceName) {
this.serviceName = serviceName;
}
}
package search;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
//定时服务
public class SchContainer {
ThreadPoolExecutor tpl;
List<SchTask> taskList;
void init(){
tpl =new ThreadPoolExecutor(5, 50, 50l, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(500));
//此处开始可通过xml配置更多的定时任务来实现
taskList = new ArrayList<SchTask>();
SchTask r = new SchTask();
r.setTimeout(3000l);
r.setPreTime(new java.util.Date());
r.setRunning(false);
taskList.add(r);
}
void start(){
while(true){
long l1 = System.currentTimeMillis();
for(SchTask r : taskList){
if(!r.isRunning()&&r.isTrue()){
tpl.submit(r);
r.setRunning(true);
}
}
long l2 = System.currentTimeMillis();
try {
if (l2 - l1 < 1000L)
Thread.sleep(1000L);
}
catch (InterruptedException localInterruptedException) {
}
}
}
public static void main(String[] args) {
SchContainer sc = new SchContainer();
sc.init();
sc.start();
}
}
package search;
public class PubUtil {
//定时任务业务逻辑
public static void callServie(String tradeCode, String serviceName) {
System.out.println("定时任务业务逻辑");
}
}
转载自原文链接, 如需删除请联系管理员。
原文链接:java中写可配置化定时任务思路,转载请注明来源!