Main Initializes Start Timer Tasks Using AddHostedService

Keywords: C#

This method is mainly used to do a timed task after the project starts directly, then you can inject your timed execution class directly into the Host host, which will perform the timed task by default after the project starts
Host can contain multiple instances of the IHostedService service.Of course, one of the Web applications is WebHost.Once the Host is up, all the added IHostedService services are started in turn
Worker is a service program that we define ourselves.When the whole system runs, it automatically calls the Worker.StartAsync() method

public class Program
    {
      
        public static void Main(string[] args)
        {
            CreateHostBuilder(args).Build().Run();
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                }).ConfigureServices((hostContext, services) =>
                {
                    //Notice here 
                    services.AddHostedService<Worker>();
                });
        /// <summary>
        ///Note the need to inherit the IHostedService
        /// </summary>
        public class Worker : IHostedService, IDisposable
        {
            private Timer _timer;
            public static int a = 0;
            public Task StartAsync(CancellationToken cancellationToken)
            {
                _timer = new Timer(dowork, null, TimeSpan.Zero,
                  TimeSpan.FromSeconds(2));//Frequency once every two minutes
                return Task.CompletedTask;
            }

            public Task StopAsync(CancellationToken cancellationToken)
            {
                _timer?.Change(Timeout.Infinite, 0);
                return Task.CompletedTask;
            }
            public void dowork(object state)
            {
                exec();
            }
            /// <summary>
            ///Execute Code Block
            /// </summary>
            public void exec()
            {
                a++;
                Console.WriteLine("No.{0}Secondary Execution", a);
            }
            public void Dispose()
            {
                _timer?.Dispose();
            }
        }
    }

Achieving results

Small Notes

You can also use inheritance of BackgroundService instead of IHostedService. The same effect is to directly inherit BackgroundService instead of both IHostedService and IDisposable

.Net Core Tips - Hosted Services + Quartz for Scheduling Timed Tasks

background

Previously, a friend asked if the.Net Core + Linux environment had something similar to Windows services.Actually, there are two ways I know about it:

#1 Create a Web project (such as a Web API) for ASP.Net Core and start the task by adding Middleware;

#2 Create a.Net Core project, add components such as Host, Dependency Injection, Configuration, and then start the service using the Main method or middleware.

However, both methods are a bit inadequate, such as:

#1 introduces the life cycle of the Web, but in fact, we don't need the Web's functionality, such as Controller;
#2 is fine by itself, but the developer requirements are a little higher, requiring a certain understanding of all components of.Net Core, in short, a drop in the threshold.

Net Core 2.1 introduced the concept of Generic Host, which is a good solution to the shortcomings of the above two methods:

As to why you chose Quartz for scheduling, I think it might be because of your mood, because you used TopShelf+Quartz before, but Hangfire is also good.

Use Hosted Service

  1. Create a console program.
  2. Add the Host Nuget package.
  3. Add a simple Timer-based Hosted Service (for a simple demonstration) that inherits the IHostedService.
  4. Add Host related code to the Main function.
  5. View results
  6. Code parsing

a. Host configuration

.ConfigureHostConfiguration(configHost =>
{
  //Configure Root Directory

  configHost.SetBasePath(Directory.GetCurrentDirectory()); 

  //Read the host s configuration json, similar to appsetting s, do not need to comment out at this time, can be opened as needed

  //configHost.AddJsonFile("hostsettings.json", true, true); 


  //Read environment variables, Asp.Net core defaults to ASPNETCORE_As prefix, this prefix is also used here to maintain consistency

  configHost.AddEnvironmentVariables("ASPNETCORE_"); 

  //You can pass in parameters before you start the host, you don't need to comment them out, you can turn them on as needed

  //configHost.AddCommandLine(args);

})

b. App Configuration

.ConfigureAppConfiguration((hostContext, configApp) =>
{
  //Read the configuration json for the application

  configApp.AddJsonFile("appsettings.json", true); 

  //Read configuration json for application specific environments

  configApp.AddJsonFile($"appsettings.{hostContext.HostingEnvironment.EnvironmentName}.json", true); 
  
  //Read environment variables

  configApp.AddEnvironmentVariables(); 

  //You can pass in parameters before you start the host, you don't need to comment them out, you can turn them on as needed

  //configApp.AddCommandLine(args);
}) 

c. Configure service and dependency injection registrations, note: There is no Middleware configuration.

.ConfigureServices((hostContext, services) =>
{
  //Add Log Service
  services.AddLogging();
  
  //Add Timer Hosted Service
  services.AddHostedService<TimedHostedService>();
})

d. Log Configuration

.ConfigureLogging((hostContext, configLogging) =>
{
  //Output Console Log
  configLogging.AddConsole();

  //Development Environment Output Debug Log
  if (hostContext.HostingEnvironment.EnvironmentName == EnvironmentName.Development)
  {
    configLogging.AddDebug();
  }
})

e. Use the console life cycle

.UseConsoleLifetime() //Exit with Ctrl + C

Other details can be referred to:https://docs.microsoft.com/en-us/aspnet/core/fundamentals/host/generic-host?view=aspnetcore-2.1

Use Quartz

  1. Add the Host Nuget package.
Install-Package Quartz -Version 3.0.5Install-Package Quartz.Plugins -Version 3.0.5
  1. Quartz configuration.

Quartz was previously configured in quartz.config, but I prefer to use appsettings.json, so I changed the configuration from appsettings.json.

Start with a QuartzOption class:

3. Rewrite JobFactory.

4. Write Quartz Hosted Service

5. Prepare appsettings.json

6. Write a TestJob

7. Prepare Quartz's dispatch file quartz_jobs.xml

8. Register Quartz Hosted Service and TestJob

9. View results

10. Additional instructions.
The default environment for Generic Service is Production. If you want to use the Development environment, you can add environment variables to the Debug tab of project properties.

Posted by kelliethile on Mon, 06 Sep 2021 09:18:52 -0700