You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

135 lines
3.3 KiB

package xyz.wbsite.jmacro;
import cn.hutool.core.thread.ThreadUtil;
import xyz.wbsite.jmacro.base.Legend;
import xyz.wbsite.jmacro.util.DialogUtil;
import xyz.wbsite.jmacro.util.Logger;
import java.io.File;
/**
* 服务线程
*
* @author wangbing
* @version 0.0.1
* @since 1.8
*/
public class JMainService {
/**
* 单例对象
*/
private static JMainService instance;
public static synchronized JMainService getInstance() {
if (instance == null) {
JMainService.instance = new JMainService();
}
return instance;
}
/**
* 服务运行状态
*/
public boolean run;
/**
* 守护线程
*/
public DaemonThread daemonThread;
/**
* 脚本
*/
private JMacro macro;
/**
* 服务内部构造器
*/
private JMainService() {
Logger.info("初始化服务");
}
public JMacro getMacro() {
return macro;
}
public static void init(JMacro macro, File legendDir) {
getInstance().macro = macro;
Legend.setDefaultBase(legendDir);
}
public void createDaemon() {
this.daemonThread = new DaemonThread();
Logger.info("初始化守护线程");
this.daemonThread.setDaemon(true);
// 启动守护线程
this.run = true;
this.daemonThread.start();
}
public static boolean start() {
if (JMainService.getInstance().macro.getFocusRect() == null) {
JMainService.getInstance().macro.startFocus();
DialogUtil.alert("未聚焦到视口,请稍后再试!");
return false;
}
if (JMainService.getInstance().run) {
Logger.info("服务已启动");
return false;
}
// 启动服务
Logger.info("启动服务");
// 创建守护线程
JMainService.getInstance().createDaemon();
return true;
}
public static boolean stop() {
if (!JMainService.getInstance().run) {
Logger.info("服务未启动");
return false;
}
// 停止服务
JMainService.getInstance().run = false;
// 立即停止脚本
if (JMainService.getInstance().macro.isRun()) {
JMainService.getInstance().macro.stop();
}
// 关闭守护线程
JMainService.getInstance().daemonThread.interrupt();
Logger.info("停止服务");
return true;
}
/**
* 守护线程
*/
public class DaemonThread extends Thread {
@Override
public void run() {
if (macro == null) {
Logger.info("脚本未设置");
return;
}
while (run && !Thread.currentThread().isInterrupted()) {
try {
ThreadUtil.sleep(1000);
macro.start();
} catch (Exception e) {
if ((e instanceof InterruptedException) || e.getMessage().contains(InterruptedException.class.getSimpleName())) {
// 服务停止
} else {
e.printStackTrace();
Logger.info("异常中断");
}
}
}
Logger.info("服务停止,守护线程已退出");
}
}
}

Powered by TurnKey Linux.