131 lines
3.2 KiB
Java
131 lines
3.2 KiB
Java
package com.muyu.domain.model;
|
|
|
|
import lombok.AllArgsConstructor;
|
|
import lombok.Builder;
|
|
import lombok.Data;
|
|
import lombok.NoArgsConstructor;
|
|
import lombok.extern.log4j.Log4j2;
|
|
|
|
import java.util.concurrent.atomic.AtomicBoolean;
|
|
import java.util.concurrent.atomic.AtomicInteger;
|
|
|
|
/**
|
|
* @author DongZeLiang
|
|
* @version 1.0
|
|
* @description 任务执行模型
|
|
* @date 2023/12/4
|
|
*/
|
|
@Data
|
|
@Log4j2
|
|
@Builder
|
|
@NoArgsConstructor
|
|
@AllArgsConstructor
|
|
public class TaskModel {
|
|
|
|
/**
|
|
* 任务状态 默认为false状态
|
|
*/
|
|
private final AtomicBoolean unifiedStatus = new AtomicBoolean(Boolean.FALSE);
|
|
|
|
/**
|
|
* 任务是否可以执行
|
|
* @return 是否有任务执行
|
|
*/
|
|
public synchronized boolean isExecution(){
|
|
// 为true表示任务在执行
|
|
if (unifiedStatus.get()){
|
|
// 就算状态为true若执行线程为null或者线程为不活跃也可以执行也可以执行任务
|
|
return this.currentThread == null || !this.currentThread.isAlive();
|
|
}
|
|
return true;
|
|
}
|
|
|
|
/**
|
|
* 当前线程
|
|
*/
|
|
private Thread currentThread ;
|
|
/**
|
|
* 任务名称
|
|
*/
|
|
private String taskName;
|
|
/**
|
|
* 任务执行总数
|
|
*/
|
|
private Integer taskExecutionSum;
|
|
|
|
/**
|
|
* 任务执行时间
|
|
*/
|
|
private long taskStartTime;
|
|
|
|
/**
|
|
* 提交当前线程任务
|
|
* @param task 线程任务
|
|
* @param taskName 任务名称
|
|
* @param taskExecutionSum 任务总数
|
|
*/
|
|
public synchronized void submit(String taskName,Integer taskExecutionSum, Thread task){
|
|
if (!this.isExecution()){
|
|
throw new RuntimeException("["+this.taskName+"]的任务正在进行中,请等待任务执行完成再次发布一键任务");
|
|
}
|
|
unifiedStatus.set(Boolean.TRUE);
|
|
this.currentThread = task;
|
|
this.currentThread.start();
|
|
this.taskName = taskName;
|
|
this.taskExecutionSum = taskExecutionSum;
|
|
this.taskSuccessSum = new AtomicInteger();
|
|
this.taskErrorSum = new AtomicInteger();
|
|
this.taskStartTime = System.currentTimeMillis();
|
|
log.info("[{}]任务执行开始", this.taskName);
|
|
}
|
|
|
|
/**
|
|
* 执行结束
|
|
*/
|
|
public void down(){
|
|
log.info("[{}]任务执行结束,耗时:[{}]MS", this.taskName, System.currentTimeMillis() - taskStartTime);
|
|
this.currentThread = null;
|
|
this.taskName = null;
|
|
this.taskExecutionSum = 0;
|
|
this.taskSuccessSum.set(0);
|
|
this.taskErrorSum.set(0);
|
|
unifiedStatus.set(Boolean.FALSE);
|
|
}
|
|
|
|
/**
|
|
* 任务成功执行总数
|
|
*/
|
|
private AtomicInteger taskSuccessSum;
|
|
|
|
/**
|
|
* 累计成功
|
|
*/
|
|
public void incrementSuccess(){
|
|
this.taskSuccessSum.incrementAndGet();
|
|
}
|
|
/**
|
|
* 获取成功数量
|
|
*/
|
|
public int getSuccessSum(){
|
|
return this.taskSuccessSum.incrementAndGet();
|
|
}
|
|
|
|
/**
|
|
* 任务执行失败总数
|
|
*/
|
|
private AtomicInteger taskErrorSum;
|
|
|
|
/**
|
|
* 累计失败
|
|
*/
|
|
public void incrementError(){
|
|
this.taskErrorSum.incrementAndGet();
|
|
}
|
|
/**
|
|
* 获取失败数量
|
|
*/
|
|
public int getErrorSum(){
|
|
return this.taskErrorSum.incrementAndGet();
|
|
}
|
|
}
|