public void Hourly_WithoutMinute_ReturnsFormattedStringWithDefaults() { string expected = "0 * * * *"; string actual = Cron.Hourly(); Assert.Equal(expected, actual); }
public void GetDescription_CronHourly_ReturnsHourly() { string expected = "Every hour"; string actual = Cron.GetDescription(Cron.Hourly()); Assert.Equal(expected, actual); }
/// <summary> /// Setup the Hangfire jobs. /// </summary> /// <param name="app"></param> /// <param name="cache"></param> private void SetupHangfireJobs(IApplicationBuilder app, IMemoryCache cache) { Log.Logger.Information("Starting setup of Hangfire job ..."); try { using (var serviceScope = app.ApplicationServices.GetRequiredService <IServiceScopeFactory>().CreateScope()) { Log.Logger.Information("Creating Hangfire jobs for License issuance check ..."); string interval = Cron.Hourly(); if (!string.IsNullOrEmpty(Configuration["QUEUE_CHECK_INTERVAL"])) { interval = (Configuration["QUEUE_CHECK_INTERVAL"]); } RecurringJob.AddOrUpdate(() => new OneStopUtils(Configuration, cache).CheckForNewLicences(null), interval); Log.Logger.Information("Hangfire License issuance check jobs setup."); } } catch (Exception e) { StringBuilder msg = new StringBuilder(); msg.AppendLine("Failed to setup Hangfire job."); Log.Logger.Error(e, "Hangfire setup failed."); } }
public void GetDescription_CronHourlyWithMinute_ReturnsFivePasTheHour() { string expected = "At 05 minutes past the hour"; string actual = Cron.GetDescription(Cron.Hourly(5)); Assert.Equal(expected, actual); }
public void Hourly_WithMinute_ReturnsFormattedStringWithMinute() { string expected = "5 * * * *"; string actual = Cron.Hourly(5); Assert.Equal(expected, actual); }
public void AddTwoJobsAndRemoveOne() { // Mock: var recurringJobManager = Substitute.For <IRecurringJobManager>(); var jobStorage = Substitute.For <JobStorage>(); var recurringJobRepositoryMock = Substitute.For <RecurringJobRepository>(jobStorage); var recurringJobs = new List <RecurringJobDto>(); var recurringJobDto = new RecurringJobDto { Id = "jobToRemove" }; recurringJobs.Add(recurringJobDto); recurringJobRepositoryMock.GetRecurringJobs().Returns(recurringJobs); // Arrange var hourly = Cron.Hourly(); Expression <Action <string> > methodCall = text => text.ToString(); var recurringJobCleanUpManager = new RecurringJobCleanUpManager(recurringJobManager, recurringJobRepositoryMock) { EnforceRecurringJob.Create("jobrecurrent", methodCall, hourly), EnforceRecurringJob.Create("jobrecurrent2", methodCall, hourly) }; // Act recurringJobCleanUpManager.AddUpdateDeleteJobs(); // Assert recurringJobManager.Received() .AddOrUpdate("jobrecurrent", Arg.Any <Job>(), hourly, Arg.Any <RecurringJobOptions>()); recurringJobManager.Received() .AddOrUpdate("jobrecurrent2", Arg.Any <Job>(), hourly, Arg.Any <RecurringJobOptions>()); recurringJobManager.Received().RemoveIfExists("jobToRemove"); }
public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseHsts(); } app.UseHangfireServer(); app.UseAuthentication(); app.UseCors("CorsPolicy"); app.UseSwagger(); app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "Web(V1)"); }); app.UseHttpsRedirection(); app.UseHangfireDashboard("/admin/hangfire"); app.UseMvc(); var addNewsinDb = app.ApplicationServices.GetService <IAddNewsInDataBase>(); var addNewsPositiv = app.ApplicationServices.GetService <INewsAddPositivity>(); RecurringJob.AddOrUpdate(() => addNewsinDb.AddNewsRangeDatabase(), Cron.Hourly()); RecurringJob.AddOrUpdate(() => addNewsPositiv.AddPositivInNews(), Cron.Hourly()); }
/// <summary> /// </summary> protected sealed override void OnStarted() { _taskDescriptionClear = AppCore.Get <TaskSchedulingManager>().RegisterTask(new TaskRequest() { Name = "Менеджер сообщений: очистка старых записей", IsEnabled = true, UniqueKey = typeof(MessagingManager).FullName + "_ClearLastNDays", Schedules = new List <TaskSchedule>() { new TaskCronSchedule(Cron.Hourly()) { IsEnabled = true } }, ExecutionLambda = () => ClearLastNDays(), TaskOptions = TaskOptions.AllowDisabling | TaskOptions.AllowManualSchedule | TaskOptions.PreventParallelExecution }); // Попытка инициализировать все сервисы обработки сообщений, наследующиеся от IMessagingService. var types = AppCore.GetQueryTypes().Where(x => x.GetInterfaces().Contains(typeof(IMessagingServiceInternal))).ToList(); foreach (var type in types) { try { var instance = AppCore.Get <IMessagingServiceInternal>(type); if (instance != null && !_services.Contains(instance)) { _services.Add(instance); } } catch { } } }
static void Main(string[] args) { Console.WriteLine("服务开始..."); //1、配置HangFire数据库连接:首次连接数据库会自动创建12张相关的表 string conn = "server=shaocx;uid=sa;pwd=1111;database=MyDB"; GlobalConfiguration.Configuration.UseStorage(new SqlServerStorage(conn)); //2、创建任务,自动将任务信息存储到数据系统表 BackgroundJob.Enqueue <Class1>(x => x.F**k("我是鬼")); //执行一次其他类的非静态方法 RecurringJob.AddOrUpdate(() => Console.WriteLine("你好啊"), Cron.Minutely()); //每分钟执行一次控制台输出 RecurringJob.AddOrUpdate(() => Class1.FuckStatic(), Cron.Hourly(2)); //每2小时执行一次 其他类的静态方法 RecurringJob.AddOrUpdate(() => Program.DoSomething2(), Cron.Daily()); //每天执行一次 其他类的静态方法 var client = new BackgroundJobClient(); //3、开启HangFire作业服务 using (var _service = new BackgroundJobServer()) { //4、控制台等待用户输入命令结束程序,如果控制台程序结束,HangFire服务跟宿主一起停止 while (true) { string tmpCmd = Console.ReadLine(); if (tmpCmd.ToLower().Equals("exit")) { break; } else { Console.WriteLine("可输入exit结束程序!"); } } } }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app) { app.UseIISPlatformHandler(); app.UseStaticFiles(); GlobalConfiguration.Configuration.UseActivator(new AspNetJobActivator(app.ApplicationServices)); SqlServerStorage sjs = new SqlServerStorage(Configuration["Data:DefaultConnection:ConnectionString"]); JobStorage.Current = sjs; BackgroundJobServerOptions backgroundJobServerOptions = new BackgroundJobServerOptions() { Queues = new[] { "DEFAULT", "critical", "normal", "low" } }; var dashboardOptions = new DashboardOptions { AuthorizationFilters = new[] { new HangfireAuthorizationFilter() } }; app.UseHangfireDashboard("/hf", dashboardOptions, sjs); app.UseHangfireServer(backgroundJobServerOptions, sjs); RecurringJob.AddOrUpdate <HandlePackageEdits>(g => g.Run(), Cron.Hourly(30)); app.UseMvc(); }
public static string PrepareCronType(CronSelectorModel model) { switch (model.CronType) { case CronType.Daily: return(Cron.Daily(model.Hour, model.Minute)); case CronType.Hourly: return(Cron.Hourly(model.Minute)); case CronType.Minutely: return(Cron.Minutely()); case CronType.Monthly: return(Cron.Monthly(model.Day, model.Hour, model.Minute)); case CronType.Weekly: return(Cron.Weekly(DayOfWeek.Monday, model.Hour, model.Minute)); case CronType.Yearly: return(Cron.Yearly(model.Month, model.Day, model.Hour, model.Minute)); } return(string.Empty); }
public string GetCronByMinutes(long min) { var minutesTimeSpan = TimeSpan.FromMinutes(min); if (min <= 0) { return(Cron.Hourly()); } if (minutesTimeSpan.Hours == 0) { var result = string.Format("0/{0} * * * *", minutesTimeSpan.Minutes); return(result); } if (minutesTimeSpan.Hours != 0) { var result = string.Format("{0} {1} * * *", minutesTimeSpan.Minutes != 0 ? string.Format("{0}", minutesTimeSpan.Minutes) : "0", minutesTimeSpan.Hours != 0 ? string.Format("0/{0}", minutesTimeSpan.Hours) : "*"); return(result); } return(Cron.Hourly()); }
/// <summary> /// Get the cron expression from the recurring options /// </summary> /// <param name="recurringOptions"></param> /// <returns></returns> private string GetCronExpression(RecurringOption recurringOptions) { var cronExpression = string.Empty; recurringOptions.Day = recurringOptions.Day == 0 ? 1 : recurringOptions.Day; switch (recurringOptions.Recurrence) { case Recurrence.Daily: cronExpression = Cron.Daily(recurringOptions.Hour, recurringOptions.Minute); break; case Recurrence.Hourly: cronExpression = Cron.Hourly(recurringOptions.Minute); break; case Recurrence.Minutely: cronExpression = Cron.Minutely(); break; case Recurrence.Monthly: cronExpression = Cron.Monthly(recurringOptions.Day, recurringOptions.Hour, recurringOptions.Minute); break; case Recurrence.Weekly: cronExpression = Cron.Weekly(recurringOptions.DayOfWeek, recurringOptions.Hour, recurringOptions.Minute); break; case Recurrence.Yearly: cronExpression = Cron.Yearly(recurringOptions.Month, recurringOptions.Day, recurringOptions.Hour, recurringOptions.Minute); break; } return(cronExpression); }
public EnforceRecurringJobsShould() { methodCall = text => text.ToString(); safeManager = new EnforceRecurringJobs(); hourly = Cron.Hourly(); idJob = "jobrecurrent"; }
// 执行的时间表。关于 CRON 详细信息,见 https://en.wikipedia.org/wiki/Cron#CRON_expression private string ConvertToCronExpression(ScheduleCronOptions cronOptions) { switch (cronOptions.scheduleCron) { case ScheduleCron.Minutely: return(Cron.Minutely()); case ScheduleCron.Hourly: return(Cron.Hourly(cronOptions.Minute)); case ScheduleCron.Daily: return(Cron.Daily(cronOptions.Hour, cronOptions.Minute)); case ScheduleCron.Weekly: return(Cron.Weekly((DayOfWeek)cronOptions.Week, cronOptions.Hour, cronOptions.Minute)); case ScheduleCron.Monthly: return(Cron.Monthly(cronOptions.Day, cronOptions.Hour, cronOptions.Minute)); case ScheduleCron.Yearly: return(Cron.Yearly(cronOptions.Month, cronOptions.Day, cronOptions.Hour, cronOptions.Minute)); default: throw new InvalidOperationException("Can not convert the scheduleCronOptions to cron."); } }
public Task StartAsync() { //添加定时任务 //每隔一段时间触发 RecurringJob.AddOrUpdate(JobId, () => Tasks2Do(), () => Cron.Hourly()); //使用浏览器打开定时任务的网址 Process.Start("http://localHost:65238/hangfire/recurring"); return(Task.FromResult(0)); }
private void GetHangfireServers(IAppBuilder app) { GlobalConfiguration.Configuration.UseSqlServerStorage("defaultconnection"); PaytmBinding paytmBinding = new PaytmBinding(); RecurringJob.AddOrUpdate(() => paytmBinding.paytmJob(), Cron.Hourly()); app.UseHangfireServer(); app.UseHangfireDashboard(); }
private string GetCronExpression(RefreshFrequent refreshFrequent) { return(refreshFrequent switch { RefreshFrequent.Minutely => Cron.Minutely(), RefreshFrequent.Quarterly => "*/15 * * * *", RefreshFrequent.Hourly => Cron.Hourly(), RefreshFrequent.Daily => Cron.Daily(2), RefreshFrequent.Weekly => Cron.Weekly(), RefreshFrequent.Monthly => Cron.Monthly(), RefreshFrequent.Yearly => Cron.Yearly(), _ => throw new NotImplementedException() });
public void RunOnSchedule(int id, string name, string recurring, Dictionary <string, string> psParams) { var recurringSwitch = new Dictionary <string, string> { { "Minutely", Cron.Minutely() }, { "Hourly", Cron.Hourly() }, { "Weekly", Cron.Weekly() }, { "Monthly", Cron.Monthly() }, { "Yearly", Cron.Yearly() } }; RecurringJob.AddOrUpdate(id.ToString(), () => Run(name, psParams), recurringSwitch[recurring]); }
public void RunOnSchedule(int id, string name, string recurring, Dictionary <string, string> psParams, DateTime schedule) { var recurringSwitch = new Dictionary <string, string> { { "Minutely", Cron.Minutely() }, { "Hourly", Cron.Hourly(schedule.Minute) }, { "Daily", Cron.Daily(schedule.Hour, schedule.Minute) }, { "Weekly", Cron.Weekly(schedule.DayOfWeek, schedule.Hour, schedule.Minute) }, { "Monthly", Cron.Monthly(schedule.Day, schedule.Hour, schedule.Minute) }, { "Yearly", Cron.Yearly(schedule.Month, schedule.Day, schedule.Hour, schedule.Minute) } }; RecurringJob.AddOrUpdate <IJobServices>(id.ToString(), x => x.Run(name, psParams), recurringSwitch[recurring], TimeZoneInfo.Local); }
/// <summary> /// Checks for configurations and settings /// for the automated Bulk Action process /// </summary> private void AutomatedBulkActionJob() { var bulkActionSettings = campusLogicSection.BulkActionSettings; string serviceName = "Automated Bulk Action"; // validation if (bulkActionSettings == null) { NotificationService.ErrorNotification(serviceName, "Bulk Action settings are missing from the config file"); logger.Error("Bulk Action settings are missing from the config file"); return; } if (bulkActionSettings.BulkActionEnabled) { //Set reoccurance based on configs var cronValue = ""; switch (bulkActionSettings.Frequency) { case "daily": cronValue = Cron.Daily(); break; case "weekly": cronValue = Cron.Weekly(); break; case "minutes": cronValue = Cron.Minutely(); break; case "hourly": cronValue = Cron.Hourly(); break; } RecurringJob.AddOrUpdate(serviceName, () => DocumentImportService.ProcessBulkAction(new BulkActionUploadDto { FileUploadDirectory = bulkActionSettings.BulkActionUploadPath, FileArchiveDirectory = bulkActionSettings.BulkActionArchivePath, NotificationEmail = bulkActionSettings.NotificationEmail, UseSSN = bulkActionSettings.UseSSN }), cronValue); } else { RecurringJob.RemoveIfExists(serviceName); } }
internal static void ScheduleJobs(this IApplicationBuilder app) { var jobManager = app.ApplicationServices.GetRequiredService <IRecurringJobManager>(); jobManager.AddOrUpdate <NuGetCatalogImporter>( "NuGetCatalogImporter", j => j.Import(JobCancellationToken.Null), // Hangfire passes in a token on activation Cron.Hourly()); jobManager.AddOrUpdate <DailyDownloadPackageIdPublisher>( "DownloadCountImporter", j => j.Import(JobCancellationToken.Null), // Runs at 1 AM UTC Cron.Daily(1)); }
protected async void RegisterJobInHangfire(Job entity) { if (entity == null || entity.Project == null) { throw new UserFriendlyException("定时任务信息不完整"); } var projectHost = entity.Project.Host; SendRequestJobArgs args = new SendRequestJobArgs() { JobId = entity.Id, Host = projectHost, ApiUrl = entity.ApiUrl }; string cron = Cron.Daily(); switch (entity.Frequency) { case FrequencyEnum.每分钟: cron = Cron.Minutely(); break; case FrequencyEnum.每小时: cron = Cron.Hourly(); break; case FrequencyEnum.每天: cron = Cron.Daily(); break; case FrequencyEnum.每月: cron = Cron.Monthly(); break; default: break; } if (!string.IsNullOrWhiteSpace(entity.Cron)) { cron = entity.Cron; } RecurringJob.AddOrUpdate <SendRequestJob>(entity.Id.ToString(), e => e.Execute(args), cron, TimeZoneInfo.Local); }
public void Start() { logger.LogInformation("Starting bootstrapping app"); DateTime startTime = DateTime.Now; // Initialize the updaters in order double stepSize = 1.0 / 9.0; double percentLoaded = 0.0; var hangFireStatusRepository = serviceProvider.GetService <HangFireStatusRepository>(); percentLoaded = RunUpdate <PoolUpdater>(hangFireStatusRepository, percentLoaded, stepSize); percentLoaded = RunUpdate <ProjectUpdater>(hangFireStatusRepository, percentLoaded, stepSize); percentLoaded = RunUpdate <RepositoryUpdater>(hangFireStatusRepository, percentLoaded, stepSize); percentLoaded = RunUpdate <BuildDefinitionUpdater>(hangFireStatusRepository, percentLoaded, stepSize); percentLoaded = RunUpdate <BuildUpdater>(hangFireStatusRepository, percentLoaded, stepSize); percentLoaded = RunUpdate <PullRequestUpdater>(hangFireStatusRepository, percentLoaded, stepSize); percentLoaded = RunUpdate <CompletedPullRequestUpdater>(hangFireStatusRepository, percentLoaded, stepSize); percentLoaded = RunUpdate <ReleaseDefinitionUpdater>(hangFireStatusRepository, percentLoaded, stepSize); percentLoaded = RunUpdate <JobRequestUpdater>(hangFireStatusRepository, percentLoaded, stepSize); hangFireStatusRepository.SetPercentLoaded(1); hangFireStatusRepository.SetIsLoaded(true); // Slow moving things only need to be updated once an hour ScheduleJob <ProjectUpdater>(Cron.Hourly()); ScheduleJob <RepositoryUpdater>(Cron.Hourly()); ScheduleJob <PoolUpdater>(Cron.Hourly()); ScheduleJob <ReleaseDefinitionUpdater>(Cron.MinuteInterval(30)); ScheduleJob <BuildDefinitionUpdater>(Cron.MinuteInterval(30)); ScheduleJob <BuildUpdater>(Cron.MinuteInterval(3)); var quickUpdateTimer = new System.Timers.Timer(TimeSpan.FromSeconds(30).TotalMilliseconds); quickUpdateTimer.Elapsed += ExecuteJobRequestUpdater; quickUpdateTimer.AutoReset = true; quickUpdateTimer.Enabled = true; var pullRequestUpdateTime = new System.Timers.Timer(TimeSpan.FromSeconds(30).TotalMilliseconds); pullRequestUpdateTime.Elapsed += ExecutePullRequestUpdate; pullRequestUpdateTime.AutoReset = true; pullRequestUpdateTime.Enabled = true; logger.LogInformation($"Finished bootstrapping app in {DateTime.Now - startTime:g}"); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, INewsGetterService getnews, IPositivityIndexService getPosIndex) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } // Enable middleware to serve generated Swagger as a JSON endpoint. app.UseSwagger(); // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.), // specifying the Swagger JSON endpoint. app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "GreatNews V1"); }); app.UseStaticFiles(); //app.UseHttpsRedirection(); app.UseCors("CORS_Policy"); app.UseAuthentication(); app.UseMvc(); //Hangfire app.UseHangfireServer(); app.UseHangfireDashboard("/hangfire", new DashboardOptions { Authorization = new[] { new HangfireAuthorizationFilter() } }); RecurringJob.AddOrUpdate( () => getnews.AutoRefresh(), Cron.Hourly); RecurringJob.AddOrUpdate( () => getPosIndex.AddPsitiveIndexToNews(), Cron.Hourly(30)); }
/// <summary> /// Set up the jobs particular to this application /// </summary> private static void ConfigureScheduledBackgroundJobs() { var recurringJobIds = new List <string>(); // because the reminder configurations are tenant-specific and user-configurable, just schedule the job to run nightly and have it check whether it's time to send a remind for each tenant. AddRecurringJob(ProjectUpdateReminderScheduledBackgroundJob.JobName, () => ScheduledBackgroundJobLaunchHelper.RunProjectUpdateKickoffReminderScheduledBackgroundJob(), MakeDailyUtcCronJobStringFromLocalTime(1, 23), recurringJobIds); // Clean up stale FirmaSessions AddRecurringJob(CleanUpStaleFirmaSessionsJob.JobName, () => ScheduledBackgroundJobLaunchHelper.RunCleanUpStaleFirmaSessionsScheduledBackgroundJob(), Cron.Hourly(10), recurringJobIds); // Remove any jobs we haven't explicitly scheduled RemoveExtraneousJobs(recurringJobIds); }
public static void Register() { #region Hangfire配置 //GlobalConfiguration.Configuration.UseMemoryStorage(); GlobalConfiguration.Configuration.UseSqlServerStorage(ConfigurationManager.ConnectionStrings["DataContext"].ConnectionString).UseConsole(); #region 实现类注册 GlobalConfiguration.Configuration.UseAutofacActivator(AutofacConfig.Container); #endregion #region 务启动 Server = new BackgroundJobServer(new BackgroundJobServerOptions { ServerName = $"{Environment.MachineName}", //服务器名称 SchedulePollingInterval = TimeSpan.FromSeconds(1), ServerCheckInterval = TimeSpan.FromSeconds(1), WorkerCount = Environment.ProcessorCount * 2, //Queues = new[] { "masuit" } //队列名 }); #endregion #endregion HangfireHelper.CreateJob(typeof(IHangfireBackJob), nameof(HangfireBackJob.UpdateLucene)); //更新文章索引 AggregateInterviews(); //访客统计 RecurringJob.AddOrUpdate(() => Windows.ClearMemorySilent(), Cron.Hourly); //每小时清理系统内存 RecurringJob.AddOrUpdate(() => CheckLinks(), Cron.HourInterval(5)); //每5h检查友链 RecurringJob.AddOrUpdate(() => EverydayJob(), Cron.Daily, TimeZoneInfo.Local); //每天的任务 RecurringJob.AddOrUpdate(() => AggregateInterviews(), Cron.Hourly(30)); //每半小时统计访客 using (RedisHelper redisHelper = RedisHelper.GetInstance()) { if (!redisHelper.KeyExists("ArticleViewToken")) { redisHelper.SetString("ArticleViewToken", string.Empty.CreateShortToken()); //更新加密文章的密码 } } }
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { loggerFactory.AddConsole(Configuration.GetSection("Logging")); loggerFactory.AddDebug(); // Determine what kind of errors to show if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseDatabaseErrorPage(); app.UseBrowserLink(); } else { app.UseExceptionHandler("/Home/Error"); } app.UseStatusCodePagesWithRedirects("/Home/Error/{0}"); app.UseStaticFiles(); app.UseIdentity(); // Hangfire app.UseHangfireDashboard("/hangfire", new DashboardOptions { Authorization = new [] { new RoleAuthorizationFilter() } }); app.UseHangfireServer(); RecurringJob.AddOrUpdate <ScheduledTasks>(x => x.AwardUserCoins(), Cron.Daily(0)); RecurringJob.AddOrUpdate <ScheduledTasks>(x => x.CheckAnimalHealth(), Cron.Hourly(0)); // Routes app.UseSession(); app.UseMvc(routes => { routes.MapRoute( name: "area", template: "{area:exists}/{controller=Home}/{action=Index}/{id?}" ); routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}" ); }); }
public static void Init(IAppBuilder app) { GlobalConfiguration.Configuration.UseSqlServerStorage("SociatisHangfire"); app.UseHangfireDashboard("/hangfire", new DashboardOptions { Authorization = new[] { new AuthorizationFilter() } }); app.UseHangfireServer(); DateTime localHour = new DateTime(2000, 1, 1, 0, 0, 0); localHour = localHour.ToUniversalTime(); RecurringJob.AddOrUpdate("DayChange", () => TriggerDayChange(), Cron.Daily(localHour.Hour)); RecurringJob.AddOrUpdate("Hourly", () => TriggerHourChange(), Cron.Hourly(localHour.Hour)); RecurringJob.AddOrUpdate("DestroyTemp", () => TriggerHourChange(), Cron.Hourly(localHour.Hour)); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } app.UseCors(builder => builder .AllowAnyOrigin() .AllowAnyMethod() .AllowAnyHeader() .AllowCredentials() ); app.UseSwagger(); app.UseSwaggerUI(sw => { sw.SwaggerEndpoint("/swagger/v1/swagger.json", "GoodNews API v1"); }); app.UseAuthentication(); app.UseHttpsRedirection(); app.UseMvc(); app.UseHangfireServer(); app.UseHangfireDashboard("/admin/hangfire", new DashboardOptions { Authorization = new[] { new HangfireAuthorizationFilter() } }); var newsService = app.ApplicationServices.GetService <INewsService>(); RecurringJob.AddOrUpdate(() => newsService.Start(), Cron.Hourly(15)); }