[CSHARP] Creating a Simple Windows Service Using Topshelf

Chào mọi người, bài viết mình sẽ giúp mọi người tìm hiểu về thư viện Topshelf để tạo một dịch vụ Windows service trên Windows Csharp một cách nhanh chóng và dễ dàng.

[Csharp] Hướng Dẫn Tạo Windows Service Đơn Giản Bằng Topshelf

Ở bài viết này mình hướng dẫn các bạn tạo 1 dịch vụ mở dụng chạy theo danh sách thời gian mà chúng ta thêm vào.

1. Đầu tiên, các bạn cài đặt thư viện Topshelt từ Nuget
PM> Install-Package Topshelf

2. Tạo một class MyServices.cs để định nghĩa một services đơn giản

using System;
using System.Timers;

namespace MyTopshelfService
{
    public class MyService
    {
        private Timer _timer;
        private readonly string[] _scheduleTimes;

        public MyService()
        {
            // Danh sách thời gian chạy, định dạng HH:mm:ss
            _scheduleTimes = new[] { "09:00:00", "12:00:00", "15:00:00" };
        }

        public void Start()
        {
            Console.WriteLine("Service started...");
            _timer = new Timer(1000); // Kiểm tra mỗi giây
            _timer.Elapsed += OnTimerElapsed;
            _timer.Start();
        }

        public void Stop()
        {
            Console.WriteLine("Service stopped...");
            _timer?.Stop();
        }

        private void OnTimerElapsed(object sender, ElapsedEventArgs e)
        {
            var currentTime = DateTime.Now.ToString("HH:mm:ss");
            foreach (var scheduledTime in _scheduleTimes)
            {
                if (currentTime == scheduledTime)
                {
                    RunScheduledTask();
                }
            }
        }

        private void RunScheduledTask()
        {
            Console.WriteLine($"Task started at {DateTime.Now}");
            // Thêm logic công việc bạn muốn thực hiện ở đây
        }
    }
}

3. Cấu hình Topshelf.

Trong Program.cs, cấu hình Topshelf để chạy service này.
using System;
using Topshelf;

namespace MyTopshelfService
{
    class Program
    {
        static void Main(string[] args)
        {
            HostFactory.Run(x =>
            {
                x.Service<MyService>(s =>
                {
                    s.ConstructUsing(name => new MyService());
                    s.WhenStarted(tc => tc.Start());
                    s.WhenStopped(tc => tc.Stop());
                });

                x.RunAsLocalSystem();

                x.SetServiceName("MyTopshelfService");
                x.SetDisplayName("My Topshelf Service");
                x.SetDescription("A simple Topshelf service with a time-based schedule.");
            });
        }
    }
}

HostFactory.Run() sẽ quản lý vòng đời của service.

RunAsLocalSystem() cấu hình service chạy với quyền của hệ thống cục bộ.

Các phương thức SetServiceName(), SetDisplayName(), và SetDescription() thiết lập các thông tin liên quan đến service khi bạn cài đặt nó.
4. Cách cài đặt dịch vụ services và gỡ bỏ nó
Cài đặt service: MyTopshelfService.exe install
Khởi động service: MyTopshelfService.exe start

Dừng service: MyTopshelfService.exe stop
Gỡ bỏ service: MyTopshelfService.exe uninstall
Dừng service: MyTopshelfService.exe stop
Gỡ bỏ service: MyTopshelfService.exe uninstall
5. Topshelf cũng hổ trợ chúng ta ghi log một cách dễ dàng khi tích hợp với thư viện log4net, nlog

Sử dụng Log4NET

  // Install-Package Topshelf.Log4Net
HostFactory.Run(x =>
{
    x.UseLog4Net();
// .........................
});
  

Sử dụng Nlog

  // Install-Package Topshelf.NLog
HostFactory.Run(x =>
{
    x.UseNLog();
// .........................
});
  

Chúc mọi người thành công với tiện ích trên.