How to use Asp.net Core to implement timing tasks and easily solve task scheduling problems!

I. Introduction

Asp.net core is an efficient and cross-platform web framework. During the development process, we often need to perform scheduled tasks in the background, such as cleaning useless files, generating reports, and sending emails. For this requirement, we can use third-party libraries (such as Hangfire or Quartz.NET) to implement task scheduling and execution, or use the Hosting module and System.Timers.Timer class that comes with asp.net core to implement simple timing Task.

This article mainly introduces how to use the Hosting module and System.Timers.Timer class that comes with Asp.net core, and Hangfire and Quartz.NET to implement timing tasks respectively. A complete sample code will be shown, and the meaning and function of each part of the code will be explained in detail to help understand the implementation process and related knowledge points.

2. The built-in Hosting module implements task scheduling

The following will introduce step by step how to use the Hosting module and System.Timers.Timer class that comes with asp.net core to implement timing tasks.

  • Create a console application

First, create a console application in Visual Studio.

  • Add the necessary NuGet packages

Add the following NuGet packages to the project:

  • Microsoft.Extensions.Hosting.Abstractions
  • Microsoft.Extensions.Hosting

These two NuGet packages provide the Hosting module and application lifecycle management functions of asp.net core.

  • Create a HostBuilder object

Create a HostBuilder object in the Main method:

static void Main(string[] args)
{
    var builder = new HostBuilder()
            .UseConsoleLifetime()   // 控制台生命周期管理
            .ConfigureServices((hostContext, services) =>
            {
                 // 配置服务
            });
                   
    builder.Build().Run();
}

HostBuilder provides functions such as configuring application services, hosting lifecycle, configuring application configuration, and more. An application's console lifecycle management can be configured using the UseConsoleLifetime method.

  • Add a scheduled task

Add a scheduled task in the ConfigureServices method:

ConfigureServices((hostContext, services) =>
{
    // 添加定时器组件
    services.AddHostedService<MyTimer>();
});

In the above code, we added a MyTimer class to the service container, which implements the IHostedService interface.

  • Implement the IHostedService interface

Implement the IHostedService interface in the MyTimer class:

// MyTimer.cs
public class MyTimer : IHostedService, IDisposable
{
    private readonly Timer _timer;
    public MyTimer()
    {
        _timer = new Timer(DoWork, null, TimeSpan.Zero, TimeSpan.FromSeconds(5)); // 每5秒执行一次DoWork方法
    }
    public Task StartAsync(CancellationToken cancellationToken)
    {
        Console.WriteLine("定时任务已启动");
        return Task.CompletedTask;
    }
    public Task StopAsync(CancellationToken cancellationToken)
    {
        Console.WriteLine("定时任务已停止");
        return Task.CompletedTask;
    }
    public void Dispose()
    {
        _timer?.Dispose();
    }
    private void DoWork(object state)
    {
        Console.WriteLine($"定时任务执行中,当前时间:{DateTime.Now}");
    }
}

The MyTimer class inherits the IHostedService interface, which defines methods for application life cycle management. In the constructor of MyTimer, we create a timer and execute the DoWork method every 5 seconds. In the StartAsync method, output the information of "scheduled task has been started"; in the StopAsync method, output the information of "scheduled task has been stopped". The Dispose method is used to release timer resources.

  • run the application

After completing the above steps, we can run the application and observe the results of the console output.

Every 5 seconds, the console will output a message similar to "scheduled task execution, current time: 2023/06/12 15:34:48", indicating that the scheduled task is running. When we manually stop the application, the console will output the "scheduled task has been stopped" message, indicating that the scheduled task has been successfully stopped.

So far, we have successfully implemented timing tasks using the Hosting module and System.Timers.Timer class that comes with asp.net core. In practical applications, more timing tasks can be added according to requirements, and parameters such as the time interval of the timer can be adjusted.

3. Hangfire implements task scheduling

The following will introduce in detail how to use asp.net core to introduce Hangfire to implement task scheduling and execution.

  • Create an asp.net core web application

First, create an asp.net core web project in Visual Studio.

  • Add the necessary NuGet packages

Add the following NuGet packages to the project:

  • Hangfire.AspNetCore
  • Hangfire.SqlServer

These two NuGet packages provide the components and functionality required by the Hangfire framework.

  • Configure Hangfire

Configure Hangfire in the Startup.cs file:

public void ConfigureServices(IServiceCollection services)
{
    // 配置Hangfire
    GlobalConfiguration.Configuration.UseSqlServerStorage(Configuration.GetConnectionString("DefaultConnection"));
    services.AddHangfire(config => config.UseSqlServerStorage(Configuration.GetConnectionString("DefaultConnection")));
    services.AddHangfireServer();
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    // 启用Hangfire仪表板
    app.UseHangfireDashboard();

    // ...
}

In the above code, we configured Hangfire in the ConfigureServices method, and enabled the Hangfire service using the AddHangfireServer method. At the same time, we also configured for the database.

In the Configure method, in addition to enabling the Hangfire dashboard, we also need to register the Hangfire service in the middleware pipeline:

app.UseHangfireServer();
  • Add a scheduled task

Create a ScheduledTasks class in the Actions folder and add a scheduled task:

public class ScheduledTasks
{
    public void DoSomething()
    {
        Console.WriteLine("Hangfire: Doing something...");
    }

    public void DoSomethingElse()
    {
        Console.WriteLine("Hangfire: Doing something else...");
    }
}

In the above code, we created two scheduled tasks: DoSomething and DoSomethingElse.

  • Register a scheduled task

Register scheduled tasks in the ConfigureServices method:

services.AddTransient<ScheduledTasks>();

// 注册定时任务
RecurringJob.AddOrUpdate<ScheduledTasks>(x => x.DoSomething(), Cron.Minutely);
RecurringJob.AddOrUpdate<ScheduledTasks>(x => x.DoSomethingElse(), Cron.Hourly);

In the above code, we use the AddOrUpdate method to register the scheduled task. The first parameter is a delegate expression, which specifies the task to be executed; the second parameter is a Cron expression, which specifies the execution time of the task.

In the above code, we execute the DoSomething task every minute and the DoSomethingElse task every hour.

  • run the application

After completing the above steps, we can run the application to view the execution of the scheduled task in the Hangfire dashboard.

In the "Recurring jobs" tab of the dashboard, we can see the two cron jobs we just registered and their next execution time. When the task is executed, we can see information such as “Hangfire: Doing something…” or “Hangfire: Doing something else…” in the console output, indicating that the task has been successfully executed.

So far, we have successfully used asp.net core to introduce Hangfire to implement task scheduling and execution, and registered two scheduled tasks for demonstration. In practical applications, we can add more scheduled tasks according to requirements, and adjust and optimize according to specific business scenarios.

4. .net Core software sharing

Jnpf low-code is a platform for rapid application development, developed by two technical engines Java/.Net, which aims to provide visual interface design and logical arrangement, greatly reducing the development threshold. It presets a large number of out-of-the-box functions, which can be customized and assembled flexibly on demand. Stable and powerful integration capabilities, one-time design, complete multi-terminal adaptation. Jnpf provides a user-friendly open interface that can be easily integrated with various build tools and IDEs. It also supports plug-ins and custom rules, allowing developers to customize configurations according to project-specific needs and standards. More details can be found in jnpf official documentation.

Try to build an application yourself: https://www.jnpfsoft.com/?csdn

Through it, IT professionals who are weak in coding can also build personalized management applications by themselves, lowering the technical threshold. Developers can develop various application management systems with only a small amount of code or no code. Since most of them are developed using components and encapsulated interfaces, the development efficiency is greatly improved.

Guess you like

Origin blog.csdn.net/Z__7Gk/article/details/132343028