Skip to content

Commit

Permalink
Add daemon demonstrantion
Browse files Browse the repository at this point in the history
  • Loading branch information
lampo1024 committed Apr 10, 2019
1 parent d576126 commit 9175f33
Show file tree
Hide file tree
Showing 9 changed files with 253 additions and 2 deletions.
6 changes: 6 additions & 0 deletions TopshelfDemo.Client/App.config
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.2" />
</startup>
</configuration>
14 changes: 14 additions & 0 deletions TopshelfDemo.Client/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
using System;

namespace TopshelfDemo.Client
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("这是一个由[码友网]创建的ERP系统示例程序,目前正在运行...");
Console.WriteLine("技术支持:码友网(https://codedefautl.com) by Rector");
Console.ReadLine();
}
}
}
36 changes: 36 additions & 0 deletions TopshelfDemo.Client/Properties/AssemblyInfo.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;

// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("TopshelfDemo.Client")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("TopshelfDemo.Client")]
[assembly: AssemblyCopyright("Copyright © 2019")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]

// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("6c8d57bd-1708-433a-bd9c-b4b4830663cb")]

// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
53 changes: 53 additions & 0 deletions TopshelfDemo.Client/TopshelfDemo.Client.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{6C8D57BD-1708-433A-BD9C-B4B4830663CB}</ProjectGuid>
<OutputType>Exe</OutputType>
<RootNamespace>TopshelfDemo.Client</RootNamespace>
<AssemblyName>TopshelfDemo.Client</AssemblyName>
<TargetFrameworkVersion>v4.6.2</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
<Deterministic>true</Deterministic>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Net.Http" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>
<None Include="App.config" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project>
6 changes: 6 additions & 0 deletions TopshelfDemoService.sln
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ VisualStudioVersion = 16.0.28729.10
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TopshelfDemoService", "TopshelfDemoService\TopshelfDemoService.csproj", "{9C3F12DC-3192-4E4E-9CF7-15CFD568AB15}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TopshelfDemo.Client", "TopshelfDemo.Client\TopshelfDemo.Client.csproj", "{6C8D57BD-1708-433A-BD9C-B4B4830663CB}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Expand All @@ -15,6 +17,10 @@ Global
{9C3F12DC-3192-4E4E-9CF7-15CFD568AB15}.Debug|Any CPU.Build.0 = Debug|Any CPU
{9C3F12DC-3192-4E4E-9CF7-15CFD568AB15}.Release|Any CPU.ActiveCfg = Release|Any CPU
{9C3F12DC-3192-4E4E-9CF7-15CFD568AB15}.Release|Any CPU.Build.0 = Release|Any CPU
{6C8D57BD-1708-433A-BD9C-B4B4830663CB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{6C8D57BD-1708-433A-BD9C-B4B4830663CB}.Debug|Any CPU.Build.0 = Debug|Any CPU
{6C8D57BD-1708-433A-BD9C-B4B4830663CB}.Release|Any CPU.ActiveCfg = Release|Any CPU
{6C8D57BD-1708-433A-BD9C-B4B4830663CB}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
Expand Down
26 changes: 26 additions & 0 deletions TopshelfDemoService/DaemonApplicationInfo.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
namespace TopshelfDemoService
{
/// <summary>
/// 需守护的应用程序实体
/// </summary>
public class DaemonApplicationInfo
{
/// <summary>
/// 进程中显示的名称
/// </summary>
public string ProcessName { get; set; }
/// <summary>
/// 应用程序安装路径
/// </summary>
public string AppFilePath { get; set; }
/// <summary>
/// 应用程序的名称
/// </summary>
public string AppDisplayName { get; set; }

/// <summary>
/// 参数
/// </summary>
public string Args { get; set; }
}
}
51 changes: 49 additions & 2 deletions TopshelfDemoService/HealthMonitorService.cs
Original file line number Diff line number Diff line change
@@ -1,15 +1,62 @@
using System;
using System.Collections.Generic;
using System.Timers;

namespace TopshelfDemoService
{
internal class HealthMonitorService
{
/// <summary>
/// 检测周期计时器
/// </summary>
private readonly Timer _timer;
/// <summary>
/// 检测周期(秒)
/// </summary>
private int _monitorInterval = 3;
/// <summary>
/// 要守护的应用程序列表
/// </summary>
private List<DaemonApplicationInfo> _daemonApps { get; set; }

public HealthMonitorService()
{
_timer = new Timer(1000) { AutoReset = true };
_timer.Elapsed += (sender, eventArgs) => Console.WriteLine("执行系统健康检查任务,所有指标均正常。执行时间:{0}", DateTime.Now);
// 初始化要守护的应用程序列表
// 实际项目中,你可以将这里的初始化参数放到配置文件/数据库/缓存中(怎么方便怎么来)
_daemonApps = new List<DaemonApplicationInfo> {
new DaemonApplicationInfo {
ProcessName ="TopshelfDemo.Client", // 请根据你的情况填写
AppDisplayName ="TopshelfDemo Client", // 请根据你的情况填写
AppFilePath =@"D:\Projects\github\TopshelfDemoService\TopshelfDemo.Client\bin\Debug\TopshelfDemo.Client.exe" // 请根据你的情况填写
}
};
_timer = new Timer(_monitorInterval*1000) { AutoReset = true };
_timer.Elapsed += (sender, eventArgs) => Monitor();
}

/// <summary>
/// 守护应用程序的方法
/// </summary>
private void Monitor()
{
foreach (var app in _daemonApps)
{
// 判断当前进程是存已启动
if (ProcessorHelper.IsProcessExists(app.ProcessName))
{
Console.WriteLine("Application[{0}] already exists.", app.ProcessName);
return;
}
try
{
// 当前主机进程列表中没有需要守护的进程名称,则启动这个进程对应的应用程序
ProcessorHelper.RunProcess(app.AppFilePath, app.Args);
}
catch (Exception ex)
{
Console.WriteLine("Start application failed:{0}", ex);
}
}
}

public void Start()
Expand Down
61 changes: 61 additions & 0 deletions TopshelfDemoService/ProcessorHelper.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;

namespace TopshelfDemoService
{
/// <summary>
/// 进程处理帮助类
/// </summary>
internal class ProcessorHelper
{
/// <summary>
/// 获取当前计算机所有的进程列表(集合)
/// </summary>
/// <returns></returns>
public static List<Process> GetProcessList()
{
return GetProcesses().ToList();
}

/// <summary>
/// 获取当前计算机所有的进程列表(数组)
/// </summary>
/// <returns></returns>
public static Process[] GetProcesses()
{
var processList = Process.GetProcesses();
return processList;
}

/// <summary>
/// 判断指定的进程是否存在
/// </summary>
/// <param name="processName"></param>
/// <returns></returns>
public static bool IsProcessExists(string processName)
{
return Process.GetProcessesByName(processName).Length > 0;
}

/// <summary>
/// 启动一个指定路径的应用程序
/// </summary>
/// <param name="applicationPath"></param>
/// <param name="args"></param>
public static void RunProcess(string applicationPath, string args = "")
{
try
{
var psi = new ProcessStartInfo
{
FileName = applicationPath,
WindowStyle = ProcessWindowStyle.Normal,
Arguments = args
};
Process.Start(psi);
}
catch{}
}
}
}
2 changes: 2 additions & 0 deletions TopshelfDemoService/TopshelfDemoService.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -48,8 +48,10 @@
</Reference>
</ItemGroup>
<ItemGroup>
<Compile Include="DaemonApplicationInfo.cs" />
<Compile Include="HealthMonitorService.cs" />
<Compile Include="MyServiceConfigure.cs" />
<Compile Include="ProcessorHelper.cs" />
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
Expand Down

0 comments on commit 9175f33

Please sign in to comment.