.NET API add Worker Service

Background Service, auto run service

Startup.cs

services.AddHostedService<WorkerService>();

WorkerService.cs

using Microsoft.Extensions.Hosting;
using System.Threading.Tasks;
using System.Threading;
using System;
using Microsoft.Extensions.Logging;
using NWIWasteWebAPI.Repositories.Models.PagedList;
using SuperSimpleTcp;
using System.Text;
using NuGet.Protocol;

namespace NWIWasteWebAPI.System.API.Services
{
    public class WorkerService: BackgroundService
    {

        SimpleTcpClient client = new SimpleTcpClient("192.168.0.168:8888");

        [Obsolete]
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            while (!stoppingToken.IsCancellationRequested)
            {
                Console.WriteLine("Executing background task running at "+ DateTimeOffset.Now.ToString());

                localTimeZone();
 

                await Task.Delay(5000, stoppingToken);
                if (client.IsConnected)
                {
                    TCPDisconnect();
                }
                else
                {
                    TCPConnect();
                }
            }
        }

        [Obsolete]
        private void localTimeZone()
        {
            const string dataFmt = "{0,-30}{1}";
            const string timeFmt = "{0,-30}{1:dd/MM/yyyy HH:mm}";
            TimeZone curTimeZone = TimeZone.CurrentTimeZone;
            // What is TimeZone name?  
            Console.WriteLine(dataFmt, "TimeZone Name:", curTimeZone.StandardName);

            // What is GMT (also called Coordinated Universal Time (UTC)  
            DateTime curUTC = curTimeZone.ToUniversalTime(DateTime.Now);
            Console.WriteLine(timeFmt, "Coordinated Universal Time:", curUTC);
            // What is GMT/UTC offset ?  
            TimeSpan currentOffset = curTimeZone.GetUtcOffset(DateTime.Now);
            Console.WriteLine(dataFmt, "UTC offset:", currentOffset);



            // Step 1: get current time zone.
            var zone = TimeZoneInfo.Local;
            Console.WriteLine("Local DisplayName: "+zone.DisplayName);
            Console.WriteLine(" -------------------------------- ");
            // Step 2: get offset. (The hours change from UTC)
            TimeSpan offset = zone.GetUtcOffset(DateTime.Now);
            Console.WriteLine("offset:"+offset);

            // Get utc.
            var zone2 = TimeZoneInfo.Utc;
            Console.WriteLine("zone display name:"+zone2.DisplayName);
            Console.WriteLine(" -------------------------------- ");
        }

        private void TCPConnect()
        {
             // set events
            client.Events.Connected += Connected;
            client.Events.Disconnected += Disconnected;
            client.Events.DataReceived += DataReceived;

            // let's go!
            client.Connect();

            // once connected to the server...
            //   client.Send("Hello, world!");
            Console.WriteLine($"start connection");

            
        }


        private void TCPDisconnect()
        {
            client.Disconnect();
            Console.WriteLine($"stop connection");
        }

        [Obsolete]
        static void Connected(object sender, ConnectionEventArgs e)
        {
            Console.WriteLine($"*** Server {e.IpPort} connected");

      }

        static void Disconnected(object sender, ConnectionEventArgs e)
        {
            Console.WriteLine($"*** Server {e.IpPort} disconnected");
        }

        static void DataReceived(object sender, DataReceivedEventArgs e)
        {
            Console.WriteLine($"[{e.IpPort}] {Encoding.UTF8.GetString(e.Data.Array, 0, e.Data.Count)}");
        }
    }
}

Last updated