-1

I want send SMS or Email or do something else in specific date and time for example in Birthday of customer at 11 am, where Datetime format birthday stored in SQL Database, by C# Blazor Server Side app. I have read https://www.codeproject.com/Articles/12117/Simulate-a-Windows-Service-using-ASP-NET-to-run-sc and C#: How to start a thread at a specific time

Is there any newer or better suggestion to do this?

Quango
  • 12,338
  • 6
  • 48
  • 83
MhD hN
  • 1
  • 3
  • 1
    It's server-side, ie ASP.NET Core, which means you can use any of the ASP.NET Core techniques you like. You can create a BackgroundService with a timer, or add a library HangFire, Coravel, Quartz.net or any other rlibrary you may like – Panagiotis Kanavos Dec 02 '20 at 19:32
  • The first link you posted is from 2005 and completely unsuitable for .NET Core. If you really wanted to create a separate service/daemon you can use the Worker template and add the appropriate Windows or Linux package to convert the worker to a service – Panagiotis Kanavos Dec 02 '20 at 19:34
  • Check [Background tasks with hosted services in ASP.NET Core](https://learn.microsoft.com/en-us/aspnet/core/fundamentals/host/hosted-services?view=aspnetcore-5.0&tabs=visual-studio) for examples of background services, including timed and queued job queues – Panagiotis Kanavos Dec 02 '20 at 19:36

1 Answers1

2

As Panagiotis Kanavos says, the Blazor server-side is an ASP.NET Core server application. ASP.NET Core has build-in library to run the background service. The ASP.NET Core could run both Blazor service and background service.

You could use Blazor to handle user input and then use background server to send Email at specific time.

More details, you could refer to this article and below code sample:

public class TestHostedService: BackgroundService
{

    private readonly ILogger _logger;

    public TestHostedService(ILoggerFactory loggerFactory)
    {
        _logger = loggerFactory.CreateLogger<TestHostedService>();
    }


    protected async override Task ExecuteAsync(
        CancellationToken cancellationToken)
    {

        do
        {
 
            if (DateTime.Now.Hour == 11)
            {
                //do something
            }
            //fired every one hour
            await Task.Delay(TimeSpan.FromHours(1), cancellationToken);
        }
        while (!cancellationToken.IsCancellationRequested);

    }
}

To run it, you should add it as HostedService.

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseStartup<Startup>();
            }).ConfigureServices((hostcontext, service) => {
                service.AddHostedService<TestHostedService>();
            });
Brando Zhang
  • 22,586
  • 6
  • 37
  • 65