简体   繁体   中英

blazor server side: How to start a thread at a specific time

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?

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>();
            });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM