当前位置:网站首页>.net core implements background tasks (scheduled tasks) longbow Tasks component (III)

.net core implements background tasks (scheduled tasks) longbow Tasks component (III)

2022-07-23 19:05:00 There is no sincerity in this matter

Link to the original text :https://www.cnblogs.com/ysmc/p/16512309.html

   In the last two articles , It briefly introduces how to use  IHostedService And  BackgroundService Achieve timed tasks , in addition to , We can also use some third-party components to achieve scheduled tasks , As you are familiar with  Quartz, Today, I will introduce another lightweight scheduled task component Longbow.Tasks,Longbow.Tasks It is also inherited  IHostedService Oh , Support cron, The component is in Gitee The open source , Interested partners can go to see , Portal ;

   It is worth mentioning that , This component also supports .NET Framework And .Net Core, Let's take a look at the official instructions :


Task task management

Task service management is  BootstrapAdmin  Built in lightweight multithread safe timed background task module , Functions are built in  Longbow.Tasks.dll  In component library , Support NETFramework 4.5+ And NETCore 2.0+

Set up

NETCore Container injection

public void ConfigureServices(IServiceCollection services)
{
    services.AddTaskServices();
}

NETFramework 4.5+

//  Program entry call 
TaskServicesManager.Init();

form

ITaskServicesFactory

Background task service factory interface , The internal implementation class is TaskServicesFactory Also inherited IHostedService So the component passes  services.AddTaskServices();  Inject task services into NETCore In the container

IScheduler

Background task scheduling interface , The internal implementation class is DefaultScheduler Be responsible for the scheduling of management tasks

ITrigger

Background task trigger interface , Three internal implementation classes are ( The default trigger fires only once )DefaultTrigger ( Periodic timing trigger )RecurringTrigger (Cron Expression triggers )CronTrigger By implementing ITrigger The interface expands the trigger by itself according to the actual business needs , Component default TriggerBuilder Responsible for creating task triggers

ITask

Background task business class interface , Only one  Task Execute(CancellationToken cancellationToken);  Method , The specific implementation of background tasks

TaskServicesOptions

Background task service configuration class

TaskServicesManager:

Background task service human-computer interaction operation class , Provide all background task operation related API


 

   First, we need to install this package , Search for  Longbow.Tasks And install

    Register this component service , Then you can use it happily ;

builder.Services.AddTaskServices();

1、 Create a class , And inheritance ITask, Implementation interface , Write the task code that needs to be executed :

public class TasksDemo : ITask
{
    public Task Execute(CancellationToken cancellationToken)
    {
        Console.WriteLine($"{DateTime.Now}");

        return Task.CompletedTask;
    }
}

2、 Where you need to start a scheduled task , Add the following code , Choose the preferred task execution method according to your own needs

 1 // Execute now , Only once 
 2 TaskServicesManager.GetOrAdd<TasksDemo>(" Mission unique identification ");
 3 
 4 // Periodic tasks  (1  Minutes later  5  Seconds to perform 2 missions )
 5 var trigger = TriggerBuilder.Default.WithInterval(TimeSpan.FromSeconds(5)).WithRepeatCount(2).WithStartTime(DateTimeOffset.Now.AddMinutes(1)).Build();
 6 
 7 TaskServicesManager.GetOrAdd<TasksDemo>(" Mission unique identification ", trigger);
 8 
 9 // Support cron expression , interval  5  Seconds to cycle through tasks 
10 TaskServicesManager.GetOrAdd<TasksDemo>(" Mission unique identification ", TriggerBuilder.Build("*/5 * * * * *"));

   It is worth mentioning that , there Cron Expression does not support year , So let's see  Longbow.Tasks The official description of :


Cron Format specification

cron Expressions are used to define fixed times 、 Mask of date and interval . Mask by seconds ( Optional )、 minute 、 Hours 、 Japan 、 The month and week fields make up . All fields allow multiple values to be specified , If all fields contain matching values , Then any given date / Time will meet the specified cron expression .

                                    Allowed values    Allowed special characters   Comment ┌───────────── second (optional) 0-59 * , - / │ ┌───────────── minute 0-59 * , - / │ │ ┌───────────── hour 0-23 * , - / │ │ │ ┌───────────── day of month 1-31 * , - / L W ? │ │ │ │ ┌───────────── month 1-12 or JAN-DEC * , - / │ │ │ │ │ ┌───────────── day of week 0-6 or SUN-SAT * , - / # L ? Both 0 and 7 means SUN │ │ │ │ │ │ * * * * * *


   Some friends may have to ask , Then how can I stop the execution of scheduled tasks , When we start the task , You need to enter the unique ID of a task , We can use this logo , Find the actuator of our task , And start it 、 Pause 、 Stop and wait operation :

var task = TaskServicesManager.Get(" Mission unique identification ");

   After obtaining the instance , Let's see what operations are provided

 1 public interface IScheduler
 2 {
 3     /// <summary>
 4     ///  get   Task scheduling name 
 5     /// </summary>
 6     string Name { get; }
 7 
 8     /// <summary>
 9     ///  get / Set up   Scheduler status 
10     /// </summary>
11     SchedulerStatus Status { get; set; }
12 
13     /// <summary>
14     ///  get   Next run time   Empty indicates that it is no longer running 
15     /// </summary>
16     DateTimeOffset? NextRuntime { get; }
17 
18     /// <summary>
19     ///  get   Last run time   When it is empty, it means it is not running 
20     /// </summary>
21     DateTimeOffset? LastRuntime { get; }
22 
23     /// <summary>
24     ///  get   Last task run result 
25     /// </summary>
26     TriggerResult LastRunResult { get; }
27 
28     /// <summary>
29     ///  get   Last run exception 
30     /// </summary>
31     Exception? Exception { get; }
32 
33     /// <summary>
34     ///  get   Scheduler creation time 
35     /// </summary>
36     DateTimeOffset CreatedTime { get; }
37 
38     /// <summary>
39     ///  get   Scheduler related triggers 
40     /// </summary>
41     IEnumerable<ITrigger> Triggers { get; }
42 
43     /// <summary>
44     ///  get   Scheduler associated tasks 
45     /// </summary>
46     ITask? Task { get; }
47 }

   Okay , That's all for this introduction , The next article will use  Longbow.Tasks Conduct practical introduction 【 Manual formation 】

At the end

Bootstrap Blazor Official website address :https://www.blazor.zone

   I hope the big guys can see this article , Can you give the project a star Under the support , Thank you !

star technological process :

1、 Visit and click the project link :BootstrapBlazor   star

2、 Click on star, Here's the picture , Can finish star, Focus on the project and don't get lost :

 

There are two more GVP project , If it's convenient for the big guys to click star Chant , Thank you very much :

  BootstrapAdmin  Project address :star
  https://gitee.com/LongbowEnterprise/BootstrapAdmin

  SliderCaptcha  Project address :star
  https://gitee.com/LongbowEnterprise/SliderCaptcha

 

Communication group (QQ) Welcome to discuss

       BA & Blazor ①(795206915)          BA & Blazor ②(675147445)

 

原网站

版权声明
本文为[There is no sincerity in this matter]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/204/202207231646447018.html