一、创建控制台服务
注意:这里的控制台程序必须要有宿主程序,不然挂载到linux服务后会出现无法启动的情况。
控制台主要代码如下
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
namespace JobDispatcherLinux
{
/// <summary>
/// 启动类
/// </summary>
class Program
{
/// <summary>
/// 启动方法
/// </summary>
/// <param name="args"></param>
static void Main(string[] args)
{
// 构造 host
var host = new HostBuilder()
.ConfigureServices((context, services) => {
services.AddHostedService<JobHostedService>(); // 添加host 服务
})
.UseConsoleLifetime()
.Build();
host.Run();
}
}
}
using AVC.Utility;
using JobDispatcherLinux.TaskJobEngine;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
namespace JobDispatcherLinux
{
/// <summary>
/// 任务宿主服务
/// </summary>
class JobHostedService : IHostedService
{
/// <summary>
/// 生命周期
/// </summary>
private readonly IHostApplicationLifetime _applicationLifetime;
/// <summary>
/// 构造
/// </summary>
public JobHostedService(IHostApplicationLifetime applicationLifetime)
{
_applicationLifetime = applicationLifetime;
}
/// <summary>
/// 启动
/// </summary>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public Task StartAsync(CancellationToken cancellationToken)
{
return Task.Run(() =>
{
_applicationLifetime.ApplicationStarted.Register(() =>
{
//
// 在程序启动时注册 具体的启动业务
//
});
_applicationLifetime.ApplicationStopped.Register(() =>
{
//
// 在程序停止前注册 具体的停止业务
//
});
Console.WriteLine("Service started!");
});
}
/// <summary>
/// 停止
/// </summary>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public Task StopAsync(CancellationToken cancellationToken)
{
Task.Run(() =>
{
Console.WriteLine("Service stopped!");
});
}
}
}
二、创建Linux服务
1. 在linux服务器 /etc/systemd/system 文件夹下创建 dotnetconsole.service 文件,并添加如下内容:
[root@localhost system]# vim dotnetconsole.service
[Unit]
Description="AVC job dispatcher"
[Service]
WorkingDirectory=/site/ServiceTest //配置工作空间
ExecStart=/usr/bin/dotnet JobDispatcherLinux.dll //配置启动命令及启动dll
Restart=always
RestartSec=10
SyslogIdentifier="AVCJobDispatcher"
User=root
Environment=ASPNETCORE_ENVIRONMENT=Production
[Install]
WantedBy=multi-user.target
2. 文件保存并退出,之后可用以下命令启动、停止、查看服务状态
systemctl daemon-reload // 创建或更新linux服务配置文件后必须运行此命令重新加载守护进程
systemctl status dotnetconsole.service // 查看服务状态
systemctl start dotnetconsole.service // 启动服务
systemctl stop dotnetconsole.service // 停止服务