C# Net6开发Linux守护进程(后台服务程序,类似Windows服务)案例

背景

在使用net6开发Linux程序时,除了AspNet Core项目外,如果是开发的一个不带Web界面,只是后台运行的控制台程序的话,默认发布到Linux系统时,如果是以start-stop-daemon方式(守护进行方式)启动运行的话,默认是不行的,程序会自动终止,因为在Linux下dotnet程序运行是以会话的方式。那么要如何实现类似Windows服务的方式在后台运行。下面就介绍一下要点吧。

C# net6开发Linux守护进程要点

1、在VS2022中新建控制台项目。
2、在项目的NuGet程序包中安装Microsoft.Extensions.Hosting依赖包。
3、修改Program.cs,以构建Host并运行,详细代码案例如下:
Program.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

namespace DataCollectServiceApp
{
    public class Program
    {
        static void Main(string[] args)
        {
            CreateHostBulder(args).Build().Run();
        }

        public static IHostBuilder CreateHostBulder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureServices((hostContext, services) =>
                {
                    services.AddHostedService<SyncService>();
                });
    }
}

SyncService.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Extensions.Hosting;

namespace DataCollectServiceApp
{
    using Wongoing.Entity;
    using Wongoing.Data.Service;

    /// <summary>
    /// 异步后台服务类
    /// </summary>
    public class SyncService : BackgroundService
    {
        #region 构造方法

        public SyncService()
        {
            
        }

        #endregion

        #region 服务启、停

        /// <summary>
        /// 服务启动
        /// </summary>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public override async Task StartAsync(CancellationToken cancellationToken)
        {
            Console.WriteLine("Press key Ctrl + C to stop the Service!");
            await base.StartAsync(cancellationToken);
        }

        /// <summary>
        /// 主定时任务
        /// </summary>
        /// <param name="stoppingToken"></param>
        /// <returns></returns>
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            while (!stoppingToken.IsCancellationRequested)
            {
                //每秒执行一次定时任务
                Console.WriteLine("执行定时任务...");
                await Task.Delay(1000, stoppingToken);
            }
        }

        /// <summary>
        /// 服务停止
        /// </summary>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public override async Task StopAsync(CancellationToken cancellationToken)
        {
            Console.WriteLine("The Service is stoped!");
            await base.StopAsync(cancellationToken);
        }

        #endregion
    }
}

要点是后台服务要使用Microsoft.Extensions.Hosting.BackgroundService。
这样的程序发布到Linux系统后,就可以通过start-stop-daemon的方式启动。

案例如下:

#!/bin/sh
# 
# Start DataCollectServiceApp
# 

start() {
	printf "Starting DataCollectServiceApp: "
	cd /opt/apps/DataCollectServiceApp
	start-stop-daemon -b -S -q -m -p /opt/apps/DataCollectServiceApp/DataCollectServiceApp.pid --exec /usr/bin/dotnet -- /opt/apps/DataCollectServiceApp/DataCollectServiceApp.dll
	echo "OK"
}

stop() {
	printf "Stopping DataCollectServiceApp: "
	start-stop-daemon -K -q -p /opt/apps/DataCollectServiceApp/DataCollectServiceApp.pid
	echo "OK"
}

case "$1" in
  start)
	start
	;;
  stop)
	stop
	;;
  restart|reload)
	stop
	start
	;;
  *)
	echo "Usage: $0 {start|stop|restart}"
	exit 1
esac

exit $?
Logo

更多推荐