.NET API Add Service
//--- worker service
services.AddHostedService<WorkerService>();
// WorkerService
using Microsoft.Extensions.Hosting;
using System.Threading.Tasks;
using System.Threading;
using System;
namespace NWIWasteWebAPI.System.API.Services
{
public class WorkerService: BackgroundService
{
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);
}
}
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(" -------------------------------- ");
}
}
}
Last updated