【问题标题】:Best approach to execute a long running task in asp.net mvc5在 asp.net mvc5 中执行长时间运行任务的最佳方法
【发布时间】:2015-12-04 00:52:14
【问题描述】:

我正在开发一个部署在 IIS 7.0 中的 asp.net mvc5 Web 应用程序 + Entity framework 6.0。目前我有一个 NetworkScanning 服务器,我将其实现为正常操作方法,可以通过 2 种方式启动:-

1.基于 global.asax 中定义的时间表:-

static void ScheduleTaskTrigger()
        {
            HttpRuntime.Cache.Add("ScheduledTaskTrigger",
                                  string.Empty,
                                  null,
                                  Cache.NoAbsoluteExpiration,
                                  TimeSpan.FromMinutes(Double.Parse(System.Web.Configuration.WebConfigurationManager.AppSettings["ScanInMinutes"])), // as defined inside the web.config
                                  CacheItemPriority.NotRemovable,
                                  new CacheItemRemovedCallback(PerformScheduledTasks));
        }

        static void PerformScheduledTasks(string key, Object value, CacheItemRemovedReason reason)
        {
            //Your TODO
            HomeController h = new HomeController();
            var c = h.ScanNetwork("***", "allscan");
            ScheduleTaskTrigger();
        }

2.或者从用户浏览器手动调用action方法。

现在 action 方法如下所示(我删除了很多代码,因为这个想法是为了提示我在 action 方法中所做的事情):-

public async Task<ActionResult> ScanNetwork(string token, string FQDN) 
        {
            string TToken = System.Web.Configuration.WebConfigurationManager.AppSettings["TToken"];//get the T token from the web.config, this should be encrypted
            var cccc = Request == null ? System.Web.Configuration.WebConfigurationManager.AppSettings["TIP"] : Request.UserHostAddress;
            if (token != TToken || cccc != System.Web.Configuration.WebConfigurationManager.AppSettings["TIP"]) 
            {


                if (FQDN != "allscan")
                { return Json(new { status = "fail", message = "Authintication failed." }, JsonRequestBehavior.AllowGet); }
                return new HttpStatusCodeResult(403, "request failed");
            }

            try
            {

              scaninfo = await repository.populateScanInfo(false); // get the info for all the servers from the database



                using (WebClient wc = new WebClient()) 
                {
                    string url = currentURL + "resources?AUTHTOKEN=" + pmtoken;
                    var json = await wc.DownloadStringTaskAsync(url);
                    resourcesinfo = JsonConvert.DeserializeObject<ResourcesInfo>(json);
                }


                foreach (var c in scaninfo) //loop through all the hypervisot server/s
                {


                    if (passwordmanagerResource.Count() == 0) // if there is not any record for the resource on the password manager
                    {


                       await repository.Save();
                        continue;

                    }
                    else if (passwordmanagerResource.Count() > 1) // if more than on record is defined for the same resource on PM
                    {


                        await repository.Save();
                        continue;

                    }
                    else
                    {



                        using (WebClient wc = new WebClient()) // call the PM API to get the account id 
                        {
                            string url = currentURL + "resources/" + passwordmanagerResourceID + "/accounts?AUTHTOKEN=" + pmtoken;
                            var json = await wc.DownloadStringTaskAsync(url);

                            resourceAccountListInfo = JsonConvert.DeserializeObject<ResourceAccountListInfo>(json);
                        }

                        using (WebClient wc = new WebClient()) // call the PM API to get the password for the account id under the related resource
                        {
                            string url = currentURL + "resources/" + passwordmanagerResourceID + "/accounts/" + passwordmanagerAccountID + "/password?AUTHTOKEN=" + pmtoken;
                            var json = await wc.DownloadStringTaskAsync(url);
                            resourceAccountPasswordListInfo = JsonConvert.DeserializeObject<ResourceAccountPasswordInfo>(json);
                        }

                        var shell = PowerShell.Create();
                        var shell2 = PowerShell.Create();
                        var shell3 = PowerShell.Create();

                        //Powercli script to get the hypervisot info
                        string PsCmd = "add-pssnapin VMware.VimAutomation.Core; $vCenterServer = '" + vCenterName + "';$vCenterAdmin = '" + vCenterUsername + "' ;$vCenterPassword = '" + vCenterPassword + "';" + System.Environment.NewLine;



                        PsCmd = PsCmd + "$VIServer = Connect-VIServer -Server $vCenterServer -User $vCenterAdmin -Password $vCenterPassword;" + System.Environment.NewLine;



                        PsCmd = PsCmd + "Get-VMHost " + System.Environment.NewLine;

                        string PsCmd2 = "add-pssnapin VMware.VimAutomation.Core; $vCenterServer = '" + vCenterName + "';$vCenterAdmin = '" + vCenterUsername + "' ;$vCenterPassword = '" + vCenterPassword + "';" + System.Environment.NewLine;



                        PsCmd2 = PsCmd2 + "$VIServer = Connect-VIServer -Server $vCenterServer -User $vCenterAdmin -Password $vCenterPassword;" + System.Environment.NewLine;



                        PsCmd2 = PsCmd2 + " Get-VMHost " + vCenterName + "| Get-VMHostNetworkAdapter -VMKernel" + System.Environment.NewLine;



                        shell.Commands.AddScript(PsCmd);
                        shell2.Commands.AddScript(PsCmd2);
                        dynamic results = shell.Invoke(); // execute the first powercli script
                        dynamic results2 = shell2.Invoke();//execute the second powercli script


                        if (results != null && results.Count > 0 && results[0].BaseObject != null) // the powercli executed successfully
                        {
                            // call the service desk API to update the hypervisor info
                            var builder = new StringBuilder();

                            XmlDocument doc = new XmlDocument();
                            using (var client = new WebClient())
                            {

                                var query = HttpUtility.ParseQueryString(string.Empty);


                              //code goes here

                                string xml = await client.DownloadStringTaskAsync(url.ToString());

                                doc.LoadXml(xml);
                                status = doc.SelectSingleNode("/operation/operationstatus").InnerText;
                                message = doc.SelectSingleNode("/operation/message").InnerText;


                            }

                        else//if the powershell script return zero result..
                        {

                            c.TServer.ScanResult = "Scan return zero result";
                            scan.Description = scan.Description + "<span style='color:red'>" + c.TServer.ScanResult + "</span><br/>";
                            await repository.Save();
                            continue;
                        }
                        if (FQDN == "allscan")
                        {

                           //code goes here
            }
            catch (WebException ex)
            {
                errormessage = "Password manager or manage engine can not be accessed";
                errorstatus = "fail";

            }
            catch (Exception e)
            {
                errormessage = "scan can not be completed. Message" + e.InnerException;
                errorstatus = "fail";

            }
            scan.EndDate = System.DateTime.Now;


                using (MailMessage mail = new MailMessage(from, "*****"))
                {
                    mail.Subject = "scan report generated";
                    //  mail.Body = emailbody;

                    mail.IsBodyHtml = true;
                    System.Text.StringBuilder mailBody = new System.Text.StringBuilder();
                    mailBody.AppendLine("<span style='font-family:Segoe UI'>Hi, <br/>");
                    mailBody.AppendLine(scan.Description);
                    mailBody.AppendLine("<br/><br/><div style='color:#f99406;font-weight:bold'>T scanning Management </div> <br/> <div style='color:#f99406;font-weight:bold'>Best Regards</div></span>");

                    SmtpClient smtp = new SmtpClient();
                    smtp.Host = System.Web.Configuration.WebConfigurationManager.AppSettings["smtpIP"];
                    smtp.EnableSsl = true;
                    mail.Body = mailBody.ToString();

                    smtp.UseDefaultCredentials = false;

                    smtp.Port = Int32.Parse(System.Web.Configuration.WebConfigurationManager.AppSettings["smtpPort"]);
                    S
                    smtp.Send(mail);
                }
            }
            return Json(new { status = errorstatus, message = errormessage }, JsonRequestBehavior.AllowGet);



        }

现在如上面的动作方法所示,它包含许多操作,例如;从数据库中检索对象,保存数据库更改,在第三方应用程序上调用 Web 客户端,运行 powercli 脚本等。现在我在 IIS 上部署了应用程序,无论是由用户手动运行还是根据计划运行,它似乎都运行良好时间。但从我自己的阅读来看,运行上述操作方法等长时间运行的任务被认为是有风险的,我需要使用不同的方法。那么任何人都可以提出为什么上述方法被认为是有风险的以及我该如何改进它? 第二个问题。现在我读到 Quartz.NET 是一种可以遵循的方法,但不确定我是否仍然可以从 Web 浏览器调用 Quartz.NET 方法并且不确定我是否可以在 Quartz.NET 中调用 webclient、执行 powercli 脚本等?

谢谢

【问题讨论】:

  • @haim770 但我不明白如果我将该方法作为操作方法或作为挂火方法运行会有什么区别?现在,如果我从 global.asax 及时调用 action 方法,它与使用 hangfire 调用它会有所不同吗?第二个问题,如果我使用hangfire,我还能从网络浏览器中调用该方法吗?请您提供更多信息?
  • Hangfire 是为这类问题而构建的,我不会在global.asax 中添加定时操作... Hangfire 可以带有一个用户界面,您可以去启动一个计划任务。查看文档,您就会明白为什么要这样做。
  • @JamieRees 现在假设我使用hangfire 或quartz.net 将网络扫描方法定义为一个及时的工作.. 然后我部署我的asp.net mvc(其中包含quartz.net 工作)在 IIS 中,quartz.net 作业会在 iis 下运行吗?或者它将在自己的二进制文件上运行?如果它将在 iis 下运行,那么我将面临与调用操作方法相同的风险,这是正确的吗?
  • 我对 quatz 不熟悉,所以无法回答。但是是的,Hangfire 将在 IIS 中的 w3wp 下运行。使用这些工具的全部意义在于您不必构建自己的调度程序。他们已经为您完成了工作并整理了警告,例如作业失败,重试循环。为什么要重新发明轮子
  • 目前在 global.asax 文件中,我定义了每 3 小时调用一次 action 方法的时间表。如果我能很好地理解您的回复,即使使用 quatz 和 hangfire 之类的工具,他们的工作也将在 iis 下运行,但这些工具相对于使用 global.asax 的优势在于它们已经为失败的工作、重试周期提供了功能。?第二个问题回到我原来的问题,在我的情况下,我有什么被认为是一种长期运行的网络扫描方法,那么使用 hangfire 或 global.asax 及时调用此方法是否被认为是一种好方法?

标签: asp.net asp.net-mvc iis asp.net-mvc-5 quartz.net


【解决方案1】:

正如有人建议的那样,Quartz.Net 的替代品可以是 Hangfire。
最后一个实现起来比 Quartz.Net 简单得多,而且它有一个漂亮的管理仪表板。

Hangfire 为您提供与 Quartz.Net 几乎相同的功能。

您可以在 Owin Startup 中引导它:

var options = new SqlServerStorageOptions
{
    PrepareSchemaIfNecessary = true,
    QueuePollInterval = TimeSpan.FromSeconds(15)
};

GlobalConfiguration.Configuration
    .UseSqlServerStorage("<your connection string here>", options)
    .UseNLogLogProvider()
    .UseActivator(new StructureMapHangfireJobActivator(My.Application.Container));

app.UseHangfireServer();

app.UseHangfireDashboard("/hangfire", new DashboardOptions
{
    AuthorizationFilters = new[] { new BpNetworkSales.Web.Infrastructure.ActionFilters.HangfireDashboardAuthorizationFilter() }
});

您可以使用您喜欢的记录器:

GlobalConfiguration.Configuration.UseNLogLogProvider();

您可以使用自己喜欢的 DI 容器:

GlobalConfiguration.Configuration.UseActivator(new StructureMapHangfireJobActivator(My.Application.Container));

您可以轻松地运行重复性任务:

RecurringJob.AddOrUpdate("RunSyncDocumentsForStatus", () => My.Application.SyncDocumentsForStatus(My.Application.CompanyCode), "0/3 * * * *");

安排延迟的工作:

Hangfire.BackgroundJob.Schedule(() => My.Application.SyncSubmittedDocuments(), TimeSpan.FromSeconds(60));

并使用属性自动重试操作:

[Hangfire.AutomaticRetry(Attempts = 5)]
public static void SyncSubmittedDocuments()
{
    ...
}

或禁用并发执行:

[Hangfire.DisableConcurrentExecution(timeoutInSeconds: 120)]
public static void SyncDocumentsForStatus(string companyCode)
{

}

这只是一个设计精美的软件;而 Quartz.Net 有点复杂,尤其是当你开始做“花哨”的事情时。

您始终必须记住,您是在 IIS 中运行这些任务,因此当 IIS 暂停或回收时,您的作业将关闭。

在您之前的问题Jay Vilalta(他对 Quartz.Net 了解很多)告诉您,替代方法是将 Quartz.Net 用作 Windows 服务。

我想如果您打算安排长时间的重复作业,并且希望在特定时间运行并且希望 100% 确定它们会被执行,那么 Windows 服务是最佳选择你有。

另一个优点是您的 ASP.NET MVC 应用程序会更流畅,因为您不会在用户日常工作时运行其他后台任务。

如果您不熟悉 Windows 服务,我建议您使用 Topshelf,它为 Quartz.Net 提供了 integration。

【讨论】:

  • 感谢您非常有帮助的回复。所以现在我明白在我的 asp.net Web 应用程序中使用quartz.net 或hangfire 不是正确的方法或者不是最强大的方法,因为它们仍然在iis 下运行。并且最好将我的长时间运行的任务编写为 Windows 服务。所以现在在我的动作方法中,我正在做这些类型的任务;运行 power-shell 脚本,使用实体框架、Web 客户端等。
  • Windows 服务会提供这些功能吗?因为之前没写过windows服务,不知道写windows服务是不是跟在asp.net mvc里面写action方法差不多?
  • 如果您可以控制您的服务器并且可以安装任何您想要的东西,Windows 服务是最好的方法。您可以在管理帐户下运行该服务,因此,您可以做任何您想做的事情。现在你可以使用Topshelf,这会让事情变得更简单。
  • 所以现在在这个链接上haacked.com/archive/2011/10/16/… 它提到最强大的方法是将长时间运行的任务作为 Windows 服务,但同时该链接提供了一些工具可以使运行长时间运行的任务在 iis 中提到的链接更健壮“...第二个原因是为了简单。如果您对我提到的限制感到满意,那么这种方法在设置网站时无需担心移动部分。无需配置外部重复任务。它只是工作......
  • 因为在我的情况下,我想要的一切都已经在我的 asp.net mvc 中,而且我之前没有编写任何 Windows 服务,所以我试图找到一种可以长时间运行的方法taks inside iis 是可能的,并且似乎有一些工具可以提高它的健壮性。但不会提供 windows 服务提供的 100% 健壮性。你觉得呢?
猜你喜欢
  • 1970-01-01
  • 2012-08-13
  • 1970-01-01
  • 2017-08-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-23
  • 2012-06-08
相关资源
最近更新 更多