代码之家  ›  专栏  ›  技术社区  ›  csch0

如何让后台工作人员在asp.net core中每5分钟更新一次数据存储

  •  0
  • csch0  · 技术社区  · 7 年前

    https://docs.microsoft.com/en-us/aspnet/core/tutorials/first-web-api-mac?view=aspnetcore-2.1

    这在Java SpringBoot或Elixir's Phoenix中非常简单。。。 在c#中有没有一种快速、无痛的方法可以做到这一点?

    我在微软网站上找到的文件是2012年的。。。因此,我认为现在有一种更优雅的方法来实现这一点。

    编辑:我使用了DNTScheduler.Core,设置起来比较轻松。遵循github repo上的exampleApp设置,下面是我最终使用的任务:

    using System;
    using System.Threading.Tasks;
    using DNTScheduler.Core.Contracts;
    using Microsoft.Extensions.Logging;
    using myapp.Models;
    
    namespace MyApp.Tasks
    {
        public class TaskOne : IScheduledTask
        {
            private readonly ILogger<DoBackupTask> _logger;
            private readonly TodoContext _context; // autoinjects since it was added in startup.cs in configure()
    
            public TaskOne(ILogger<DoBackupTask> logger, TodoContext context)
            {
                _logger = logger;
                _context = context;
            }
    
            public Task RunAsync()
            {
    
                var todo = _context.TodoItems.Find(1);
                if (todo == null)
                {
                    return Task.CompletedTask;
                }
    
                string[] names = new string[] { "val1", "val2"};
                Random r = new Random();
                string random_name = names[r.Next(0, names.Length)];
                todo.Name = random_name;
    
                _context.TodoItems.Update(todo);
                _context.SaveChanges();
                _logger.LogInformation("Ran My Task\n\n ");
    
                return Task.CompletedTask;
    
            }
        }
    }
    
    3 回复  |  直到 7 年前
        1
  •  0
  •   Abolfazl Roshanzamir    7 年前

    我建议您使用Scheduler,有一些软件包可以做到这一点,但迄今为止我看到的最好的软件包是 DNTScheduler.Core

    DNTScheduler.Core

    有关更多信息,您可以访问 this link

        2
  •  0
  •   Nicholas    7 年前

    我认为,如果你想遵循当地的做法,正确的答案是错误的。

    利用IHostedService执行重复操作。

    Here’s an answer

        3
  •  0
  •   tlt    7 年前

    我在某处读过一句谚语:“如果值得做,就值得做对。如果不值得做正确的事情,那就找一件正确的事情。”

    所以,正如其他同事已经说过的,由于前面提到的原因,web应用程序不应该是后台进程的容器。

    1. windows服务,甚至windows scheduler(在经典主机上)或用于调度的某些库,但不在web应用程序之外。然后,这些调度器(无论是哪种调度器)都可以在您的web应用程序中触发API端点,这样您就可以在一个地方拥有业务逻辑

    当你不需要的时候,几乎所有的事情都在找麻烦。

        4
  •  0
  •   David Buck Richard Ferris    5 年前

    在这个示例中,我使用 UnitOfWork 和 Repository Pattern Cannot consume scoped service *IUnitOfWork* from singleton

    1-添加 work 阶级和 IWork 界面如下:

    using System.Threading;
    using System.Threading.Tasks;
    
    namespace Map118.App.BackgroundTasks
    {
        public interface IWorker
        {
            Task DoWork(CancellationToken cancellationToken);
        }
    }
    

    using Map118.DataLayer.IRepositories;
    using Map118.Models;
    using Microsoft.Extensions.DependencyInjection; 
    using System; 
    using System.Threading;
    using System.Threading.Tasks;
    
    namespace Map118.App.BackgroundTasks
    {
        public class Worker : IWorker
        {            
            private readonly IServiceProvider serviceProvider;
            public Worker( IServiceProvider serviceProvider)
            {               
                this.serviceProvider = serviceProvider;
            }
    
            public async Task DoWork(CancellationToken stoppingToken)
            {
                while (!stoppingToken.IsCancellationRequested)
                {
                    using (var scope = serviceProvider.CreateScope())
                    {
                        var _unitOfWork = scope.ServiceProvider.GetRequiredService<IUnitOfWork>();
                        while (!stoppingToken.IsCancellationRequested)
                        {
                            WordSuggestion wordSuggestion = new WordSuggestion()
                            {
                                word = Guid.NewGuid().ToString(),
                            };
                            await _unitOfWork.wordSuggestionRepository.Add(wordSuggestion);
                            await _unitOfWork.Save();
                            await Task.Delay(1000 * 3600);
                        }
                    }
                }
            }
        }
    }
    

    2-添加另一个类,如下所示:

    using Microsoft.Extensions.Hosting;
    using System.Threading;
    using System.Threading.Tasks;
    
    namespace Map118.App.BackgroundTasks
    {
        public class UserActivitiesCleaner : BackgroundService
        {
            private readonly IWorker worker;
    
            public UserActivitiesCleaner(IWorker worker)
            {
                this.worker = worker;
            }
    
            protected override async Task ExecuteAsync(CancellationToken stoppingToken)
            {
                await worker.DoWork(stoppingToken);            
            }
        }
    }
    

    services 到 Startup.cs :

    services.AddHostedService<UserActivitiesCleaner>();
    services.AddSingleton<IWorker, Worker>();