FreeScheduler 在asp.net core 中使用依赖注入的方式进行注入使用

1. 创建 SchedulerTask.cs 类 ,代码如下

 public class SchedulerTask
 {
     private readonly ILogger<SchedulerTask> _logger;
     private readonly IServiceScopeFactory _serviceScopeFactory;public SchedulerTask(ILogger<SchedulerTask> logger, IServiceScopeFactory serviceScopeFactory)
     {
         _logger = logger;
         _serviceScopeFactory = serviceScopeFactory;
     }

     public async Task ExecuteAsync(TaskInfo task)
     {

         if (task.Topic == "test")
         {
             //调用其他服务
             using (var scope = _serviceScopeFactory.CreateScope())
             {
                 var xxx = scope.ServiceProvider.GetRequiredService<xxx>();
               
             }

         }

     }
    
 }

2.在main 函数中注入

public class Program
{
    public static void Main(string[] args)
    {
        var builder = WebApplication.CreateBuilder(args);

        builder.Services.AddControllers();
        //开始注入
        builder.Services.AddSingleton<SchedulerTask>();
        Func<IServiceProvider, Scheduler> schedulerFactory = r =>
        {
            var schedulerTask = r.GetRequiredService<SchedulerTask>();
            return new FreeSchedulerBuilder()
                .OnExecuting(task =>
                {

                     schedulerTask.ExecuteAsync(task).Wait(); //加wait 任务可以顺延
                })
                .UseTimeZone(TimeSpan.FromHours(8))
                .Build();
        };
        builder.Services.AddSingleton(schedulerFactory);
        var app = builder.Build();
        //程序启动时添加任务
        using (var scope = app.Services.CreateScope())
        {
            var scheduler = scope.ServiceProvider.GetRequiredService<Scheduler>();
            scheduler.AddTask("test", "test", -1, 3);
        }
        app.UseFreeSchedulerUI("/freescheduler/");
        app.UseAuthorization();


        app.MapControllers();

        app.Run();
    }
}

 

3. 其他地方使用

[Route("api/[controller]/[action]")]
[ApiController]
public class SchedulerController : ControllerBase
{
    private readonly Scheduler _scheduler;
    public SchedulerController(Scheduler scheduler)
    {
        _scheduler = scheduler;
    }
    [HttpGet]
    public void AddTask(string topic)
    {
        _scheduler.AddTask(topic, topic, -1, 10);
    }
}

 

posted on 2024-08-22 14:01  落叶子  阅读(22)  评论(0编辑  收藏  举报

导航