在.NET Core控制台应用程序中不会触发使用Hangfire计划的任务

时间:2019-06-15 10:20:14

标签: c# hangfire

我正在尝试在console application with Hangfire中实现方法的触发。

这是我的Program class的样子:

internal class Program
{
    private static IServiceProvider Provider { get; set; }

    private static void Main(string[] args)
    {
        Program program = new Program();
        program.ConfigureDI();

        program.InitializeScheduledJob("* * * * *");
    }

    private void ConfigureDI()
    {
        var configuration = GetConfiguration();

        var services = new ServiceCollection();

        services.AddSingleton<IConfiguration>(configuration);

        services.AddScoped<ITestService, TestService>();

        Provider = services.BuildServiceProvider();
    }

    private IConfigurationRoot GetConfiguration()
    {
        var environmentName = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");

        var configurationBuilder = new ConfigurationBuilder();
        configurationBuilder.AddJsonFile($"appsettings.{environmentName}.json", true, true);

        return configurationBuilder.Build();
    }

    private void InitializeScheduledJob(string cron)
    {
        var testService = Provider.GetService<ITestService>();
        var configuration = Provider.GetService<IConfiguration>();

        var scheduledJobId = configuration.GetSection("ScheduledJobId");
        var hangfireConnectionString = configuration.GetSection("ConnectionStrings:HangfireConnection");

        GlobalConfiguration.Configuration.UsePostgreSqlStorage(hangfireConnectionString.Value, new PostgreSqlStorageOptions { QueuePollInterval = TimeSpan.FromSeconds(1) });

        using (var server = new BackgroundJobServer())
        {
            RecurringJob.AddOrUpdate(scheduledJobId.Value, () => testService.TestMethodAsync(), cron);
        }
    }
}

如您所见,我在应用程序中使用DI,并且试图在TestMethodAsync服务中调用TestService方法,但是尽管将其添加为重复性工作,却从未被调用。

可能是什么问题?

0 个答案:

没有答案