1.@Service修饰类名,同时类继承Thread类

@Service
public class MasterSchedulerService extends Thread { /**
* logger of MasterSchedulerService
*/
private static final Logger logger = LoggerFactory.getLogger(MasterSchedulerService.class); @Autowired
private ServerConfig serverConfig; /**
* dolphinscheduler database interface
*/
@Autowired
private ProcessService processService; /**
* zookeeper master client
*/
@Autowired
private ZKClient zkClient; /**
* master exec service
*/
private ThreadPoolExecutor masterExecService; @Autowired
private FamaVmMapper vmMapper; /**
* constructor of MasterSchedulerService
*/
@PostConstruct
public void init(){
this.masterExecService = (ThreadPoolExecutor) ThreadUtils.newDaemonFixedThreadExecutor("Server-Thread"
, serverConfig.getMasterExecThreads());
} @Override
public synchronized void start(){
super.setName("MasterSchedulerService");
super.start();
} public void close() {
masterExecService.shutdown();
boolean terminated = false;
try {
terminated = masterExecService.awaitTermination(5, TimeUnit.SECONDS);
} catch (InterruptedException ignore) {
Thread.currentThread().interrupt();
}
if(!terminated){
logger.warn("masterExecService shutdown without terminated, increase await time");
}
logger.info("master schedule service stopped...");
} /**
* run of MasterSchedulerService
*/
@Override
public void run() {
logger.info("master scheduler started");
while (Stopper.isRunning()){
try {
if (zkClient.getZkClient().getState() == CuratorFrameworkState.STARTED) {
scheduleProcess();
}
} catch (Exception e) {
logger.error("master scheduler thread error", e);
}
}
} private void scheduleProcess() throws Exception {
InterProcessMutex mutex = null;
try {
mutex = zkClient.blockAcquireMutex(); // make sure to scan and delete command table in one transaction
Command command = processService.findOneCommand();
if (command != null) {
logger.info("find one command: {}", JsonUtils.toJSONString(command)); try {
String address = getLocalAddress();
ResourceInstance processInstance = processService.handleCommand(address,command);
logger.info("processInstance: {}", JsonUtils.toJSONString(processInstance));
if (processInstance != null) {
MapperContext context = new MapperContext();
context.vmMapper = vmMapper;
MasterExecThread execThread = new MasterExecThread(
processInstance
, processService
, serverConfig
, context);
masterExecService.execute(execThread);
}
} catch (Exception e) {
logger.error("Command consumer error ", e);
// processService.moveToErrorCommand(command, e.toString());
}
} else {
//indicate that no command ,sleep for 1s
Thread.sleep(Constants.SLEEP_TIME_MILLIS);
}
} finally {
zkClient.releaseMutex(mutex);
}
} private String getLocalAddress() {
return NetUtils.getAddr(serverConfig.getListenPort());
}
}

2.执行时,直接执行start方法

@ComponentScan(value = {"fama.cost"})
public class FamaServerApplication implements IStoppable { private static final Logger logger = LoggerFactory.getLogger(FamaServerApplication.class); @Autowired
private MasterSchedulerService schedulerService; @Autowired
private SpringApplicationContext springApplicationContext; @Autowired
private BeanContext beanContext; @Autowired
private ZKClient zkClient; public static void main(String[] args) {
Thread.currentThread().setName("Schedule-Server");
new SpringApplicationBuilder(FamaServerApplication.class).web(WebApplicationType.NONE).run(args);
int currentProcessPid = getProcessID();
logger.info("Current Process Pid : {}",currentProcessPid);
} @PostConstruct
public void run() {
this.zkClient.start(this);
this.schedulerService.start();
try {
logger.info("start Quartz server...");
QuartzExecutors.getInstance().start();
} catch (Exception e) {
try {
QuartzExecutors.getInstance().shutdown();
} catch (SchedulerException e1) {
logger.error("QuartzExecutors shutdown failed : " + e1.getMessage(), e1);
}
logger.error("start Quartz failed", e);
} Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
@Override
public void run() {
if (Stopper.isRunning()) {
close("shutdownHook");
}
}
}));
} public void close(String cause) { try {
//execute only once
if (Stopper.isStopped()) {
return;
} logger.info("master server is stopping ..., cause : {}", cause); // set stop signal is true
Stopper.stop(); try {
//thread sleep 3 seconds for thread quietly stop
Thread.sleep(3000L);
} catch (Exception e) {
logger.warn("thread sleep exception ", e);
}
//close
this.schedulerService.close();
this.zkClient.close();
//close quartz
try {
QuartzExecutors.getInstance().shutdown();
logger.info("Quartz service stopped");
} catch (Exception e) {
logger.warn("Quartz service stopped exception:{}", e.getMessage());
}
} catch (Exception e) {
logger.error("master server stop exception ", e);
} finally {
// System.exit(-1);
}
} @Override
public void stop(String cause) {
close(cause);
} public static final int getProcessID() {
try {
RuntimeMXBean runtimeMXBean = ManagementFactory.getRuntimeMXBean();
return Integer.valueOf(runtimeMXBean.getName().split("@")[0]).intValue();
}catch (Exception ex){
logger.error(ex.getMessage(),ex);
return 0;
}
}
}

单线程service服务的更多相关文章

  1. 解决VMWARE NAT SERVICE服务无法启动或服务消失的问题

    解决VMWARE NAT SERVICE服务无法启动或服务消失的问题 2016-02-02 11:18 2012人阅读 评论(2) 收藏 举报  分类: 网络通信(3)  今日使用VMware中的Wi ...

  2. 使用axis开发web service服务端

    一.axis环境搭建 1.安装环境 JDK.Tomcat或Resin.eclipse等. 2.到 http://www.apache.org/dyn/closer.cgi/ws/axis/1_4下载A ...

  3. win7提示“User Profile Service服务未能登录”

    注:本文由Colin撰写,版权所有!转载请注明原文地址,谢谢合作! 最近,有个同事打电话告诉我说他的用户名无法登陆到系统,提示“User Profile Service服务未能登录,无法加载用户配置文 ...

  4. Android 通过JNI实现守护进程,使得Service服务不被杀死

    来自: http://finalshares.com/read-7306 转载请注明出处: http://blog.csdn.net/yyh352091626/article/details/5054 ...

  5. Service服务

    Android多线程: 定义线程的2种方式: 1.继承Thread类,重写run()方法,new一个实例,用start()方法启动:new MyThread().start(); 2.实现Runnab ...

  6. Centos6.5 设置Tomcat8 service服务实现自启动和服务管理

    Centos6.5 设置Tomcat8 service服务实现自启动和服务管理 将tomcat设置成像apache,nginx一样. 用serviec xxxx start/stop/restart ...

  7. Android 综合揭秘 —— 全面剖释 Service 服务

    引言 Service 服务是 Android 系统最常用的四大部件之一,Android 支持 Service 服务的原因主要目的有两个,一是简化后台任务的实现,二是实现在同一台设备当中跨进程的远程信息 ...

  8. win8.1 user profile service 服务登录失败

    在Win 8.1 上新建个用户后,不能登录. 出现 user profile service 服务登录失败. 无法加载用户配置文件. 网上大部分相同提示的问题是有关已有账号不能再次登陆的. 解决方式是 ...

  9. Android中Service(服务)详解

    http://blog.csdn.net/ryantang03/article/details/7770939 Android中Service(服务)详解 标签: serviceandroidappl ...

随机推荐

  1. 数据结构(5):Java实现二叉树

    二叉树图: package com.test.Sort; import java.util.ArrayList; import java.util.LinkedList; public class B ...

  2. OO第一单元总结——求导

    一.基于度量分析程序结构 (一)第一次作业 (1)设计思路 本次作业只涉及到简单幂函数通过加减运算而复合而成的函数,因此笔者自然的把函数分成了函数本体以及单个的项两个部分,在笔者的设计中两个类的功能如 ...

  3. 1028 List Sorting

    Excel can sort records according to any column. Now you are supposed to imitate this function. Input ...

  4. G - Number Transformation(BFS+素数)

    In this problem, you are given an integer number s. You can transform any integer number A to anothe ...

  5. input 的各种属性的验证 checkValidity兼容性

    <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title&g ...

  6. SpringCloud之服务网关Gateway,入门+实操

    SpringCloudAlibaba微服务实战教程系列 Spring Cloud 微服务架构学习记录与示例 一. GateWay简介 Spring Cloud GateWay是Spring Cloud ...

  7. Win64 驱动内核编程-4.内核里操作字符串

    内核里操作字符串 字符串本质上就是一段内存,之所以和内存使用分开讲,是因为内核里的字符串太有花 样了,细数下来竟然有 4 种字符串!这四种字符串,分别是:CHAR*.WCHAR*.ANSI_STRIN ...

  8. 【python】Leetcode每日一题-扁平化嵌套列表迭代器

    [python]Leetcode每日一题-扁平化嵌套列表迭代器 [题目描述] 给你一个嵌套的整型列表.请你设计一个迭代器,使其能够遍历这个整型列表中的所有整数. 列表中的每一项或者为一个整数,或者是另 ...

  9. springboot项目部署(war包)

    将springboot项目打包成war,并且部署到tomcat.比较麻烦,自己踩的坑也比较多.算了一下,找bug的时间,有两天熬到凌晨2点. 修改pom.xml使得打包成war <groupId ...

  10. 【maven】Failed to execute goal org.apache.maven.plugins:maven-site-plugin:3.3:site (default-site)

    问题描述 site一点击就报错,如下 Failed to execute goal org.apache.maven.plugins:maven-site-plugin:3.3:site (defau ...