package com.example.jmacro.wjdr; import cn.hutool.core.thread.ThreadUtil; import com.example.jmacro.wjdr.demo.DemoThread; import com.example.jmacro.wjdr.util.Logger; import java.awt.*; import java.io.File; /** * 主线程 * * @author wangbing * @version 0.0.1 * @since 1.8 */ public class JMainService { private static JMainService instance; private JMacroThread thread; private JMainService() throws AWTException { // 脚本初始化 Logger.info("初始化脚本"); jMacro = new JMacro(); thread = new DemoThread(jMacro); } public static synchronized JMainService getInstance() throws AWTException { if (instance == null) { JMainService.instance = new JMainService(); } return instance; } public JMacroThread getThread() { return thread; } public JMacro getMacro() { return jMacro; } /** * 脚本对象 */ private final JMacro jMacro; /** * 服务运行状态 */ private boolean run; public static void start() throws AWTException { // 启动服务 Logger.info("启动服务"); JMainService.getInstance().run = true; // 启动后台线程 JMainService.getInstance().serviceThread.start(); } public static void stop() throws AWTException { Logger.info("停止服务"); JMainService.getInstance().run = false; JMainService.getInstance().serviceThread.interrupt(); } /** * 设置图例路径 * * @param legend 图例路径 */ public void setLegend(File legend) { if (this.jMacro != null) { this.jMacro.setLegend(legend); } } /** * 服务线程 */ public Thread serviceThread = new Thread() { @Override public void run() { while (run) { ThreadUtil.sleep(1000); if (thread == null) { Logger.error("脚本线程未设置"); continue; } thread.run(); // 立即执行 // if (noDelay) { // if (schedule != null) { // schedule.cancel(true); // } // // noDelay = false; // Logger.info("启动线程"); // schedule = TaskUtil.schedule(new MacroThread(jMacro), 0, TimeUnit.SECONDS); // continue; // } // if (schedule != null) { // continue; // } // // if (DateUtil.isIn(DateUtil.date(), DateUtil.parse(workStart), DateUtil.parse(workEnd))) { // int delay = RandomUtil.randomInt(5, 20); // Logger.info("等待{}分钟后,重新启动线程", delay); // schedule = TaskUtil.schedule(new MacroThread(jMacro), delay, TimeUnit.MINUTES); // } } } }; /** * 启动入口 */ public static void main(String[] args) throws AWTException { new JMainService().start(); } }