gpt4 book ai didi

c# - asp.net 上的 HangFire 重复性工作

转载 作者:行者123 更新时间:2023-11-30 21:38:39 25 4
gpt4 key购买 nike

我开始使用 HangFire 每 X 分钟/小时处理一次任务,我需要添加重复性作业。在控制台应用程序中,我设法做得很好,但在 asp.net 上,我只能通过 BackgroundJob.Enqueue 方法让它工作一次。

public class Global : HttpApplication
{
private static string LigacaoBD = myConn;
private static ApiMethods sportRadar = new ApiMethods();
private static Jogo jogo = new Jogo(LigacaoBD);
private static List<SportRadar.ClassesCliente.Jogo> jogos;
private static List<SportRadar.ClassesCliente.Competicao> competicoes;

void Application_Start(object sender, EventArgs e)
{
// Code that runs on application startup
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);

GlobalConfiguration.Configuration.UseSqlServerStorage(LigacaoBD);

using (var connection = JobStorage.Current.GetConnection())
{
foreach (var recurringJob in connection.GetRecurringJobs())
{
RecurringJob.RemoveIfExists(recurringJob.Id);
}
}

using (var server = new BackgroundJobServer())
{
// This works just fine
var id=BackgroundJob.Enqueue(() => Actualizacoes());
// This does not.
// I even checked the DB for job queue or something but couldn't find anything
RecurringJob.AddOrUpdate(id, () => Actualizacoes(), Cron.Minutely);
}
}



public void Actualizacoes()
{
// Stuff I need to do regularly
}
}

我以为我做对了,但显然我这里有问题。您认为问题出在哪里?

最佳答案

有两个问题。

一个。因为您正在传递 id - 这在您的实现中是不必要的。

BackgroundJob.Enqueue 返回作业的唯一标识符。在您的代码中,此作业已排队并执行。

改变

RecurringJob.AddOrUpdate(id, () => Actualizacoes(), Cron.Minutely);

RecurringJob.AddOrUpdate(() => Actualizacoes(), Cron.Minutely);

此外,您将 BackgroundJobServer 的创建包装在 using 语句中。然后在那里创建工作。因此,BackgroundJobServer 正在被 GC 清除。

相反,试试这个:

public class Global : HttpApplication
{
private static string LigacaoBD = myConn;
private static ApiMethods sportRadar = new ApiMethods();
private static Jogo jogo = new Jogo(LigacaoBD);
private static List<SportRadar.ClassesCliente.Jogo> jogos;
private static List<SportRadar.ClassesCliente.Competicao> competicoes;

private BackgroundJobServer _backgroundJobServer;

void Application_Start(object sender, EventArgs e)
{
// Code that runs on application startup
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);

GlobalConfiguration.Configuration.UseSqlServerStorage(LigacaoBD);

using (var connection = JobStorage.Current.GetConnection())
{
foreach (var recurringJob in connection.GetRecurringJobs())
{
RecurringJob.RemoveIfExists(recurringJob.Id);
}
}

//create an instance of BackgroundJobServer
_backgroundJobServer = new BackgroundJobServer();

//add your recurring job
RecurringJob.AddOrUpdate(() => Actualizacoes(), Cron.Minutely);
}
}

关于c# - asp.net 上的 HangFire 重复性工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45801463/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com