public static void RegisterAsRecurring(string jobName, string cronExpression) { RecurringJob.AddOrUpdate <TJob>(jobName, job => job.Run(), cronExpression); }
public void StartJobs() { RecurringJob.AddOrUpdate(() => DownloadProducts(), CronExpression); }
public void CreateRecurringJob() { GlobalConfiguration.Configuration.UseSqlServerStorage("db"); RecurringJob.AddOrUpdate(() => RecurringMethod("Recurring task", 1), Cron.MinuteInterval(1), onlyIfLastFinishedOrFailed: true); }
public IActionResult Invoice(string userName) { RecurringJob.AddOrUpdate(() => SendInvoiceMail(userName), Cron.Monthly); return(Ok($"Recurring Job Scheduled. Invoice will be mailed Monthly for {userName}!")); }
/// <summary> /// Removes the Hangfire task if it exists. /// </summary> /// <param name="jobId"> /// Hangfire task id. /// </param> protected virtual void RemoveIfExists(string jobId) { RecurringJob.RemoveIfExists(jobId); }
// action 必须是 public 方法 public void AddTask(Expression <Action> action, ScheduleCronOptions cronOptions) { var cron = this.ConvertToCronExpression(cronOptions); RecurringJob.AddOrUpdate(action, cron); }
/// <summary> /// 定时(循环)任务代表可以重复性执行多次,支持CRON表达式 /// </summary> public void SetTestRegisterAddOrUpdateJobs() { RecurringJob.AddOrUpdate(() => this.OnTimeTestRegister("AddOrUpdate"), "* */6 * * *"); }
public static void SetJobs() { RecurringJob.AddOrUpdate <ResetUserAndMenuDataJob>("定时重置系统用户和菜单数据", j => j.Run(), Cron.Daily); RecurringJob.AddOrUpdate <WriteOperateLogJob>("定时写入操作日志", j => j.Run(), Cron.Minutely); RecurringJob.AddOrUpdate <ClearOperateLogJob>("定时清理操作日志", j => j.Run(), Cron.Daily); }
public void AddOrUpdate<T>(string recurringJobId, Expression<Func<T, Task>> methodCall, string cronExpression, TimeZoneInfo timeZone = null, string queue = "default") { RecurringJob.AddOrUpdate(recurringJobId, methodCall, cronExpression, timeZone, queue); }
public static IApplicationBuilder UseNotifications(this IApplicationBuilder app, IConfigurationRoot configuration) { RecurringJob.AddOrUpdate <SendNotificationService>("SendNotificationService", service => service.NotificationEmailMonitor(), Cron.MinuteInterval(5)); return(app); }
public static void AddOrUpdateJob() { RecurringJob.AddOrUpdate(() => Dispatch(), Cron.Daily); }
public static void Main() { //The path to the Realm DB file. string dbPath = Path.Combine( Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "Hangfire.Realm.Sample.NetCore.realm"); Console.WriteLine($"Using database {dbPath}"); //A standard Realm configuration. RealmConfiguration realmConfiguration = new RealmConfiguration(dbPath) { ShouldCompactOnLaunch = (totalBytes, usedBytes) => { // Compact if the file is over 100MB in size and less than 50% 'used' var oneHundredMB = (ulong)(100 * 1024 * 1024); return(totalBytes > oneHundredMB && (double)usedBytes / totalBytes < 0.5); }, }; //Hangfire.Realm storage options. RealmJobStorageOptions storageOptions = new RealmJobStorageOptions { RealmConfiguration = realmConfiguration, //Required. QueuePollInterval = TimeSpan.FromSeconds(1), //Optional. Defaults to TimeSpan.FromSeconds(15) //SlidingInvisibilityTimeout = TimeSpan.FromSeconds(10), //Optional. Defaults to TimeSpan.FromMinutes(10) JobExpirationCheckInterval = TimeSpan.FromMinutes(1) //Optional. Defaults to TimeSpan.FromMinutes(30) }; //Standard Hangfire server options. BackgroundJobServerOptions serverOptions = new BackgroundJobServerOptions() { WorkerCount = 40, Queues = new[] { "default" }, ServerTimeout = TimeSpan.FromMinutes(10), HeartbeatInterval = TimeSpan.FromSeconds(60), ServerCheckInterval = TimeSpan.FromSeconds(10), SchedulePollingInterval = TimeSpan.FromSeconds(10), }; //Hangfire global configuration GlobalConfiguration.Configuration .UseLogProvider(new ColouredConsoleLogProvider(Logging.LogLevel.Debug)) .UseRealmJobStorage(storageOptions); using (new BackgroundJobServer(serverOptions)) { //Queue a bunch of fire-and-forget jobs for (var i = 0; i < JobCount; i++) { var jobNumber = i + 1; BackgroundJob.Enqueue <FafJob>((_) => _.Execute(jobNumber, CancellationToken.None)); } //A scheduled job that will run 1.5 minutes after being placed in queue BackgroundJob.Schedule(() => Console.WriteLine("A Scheduled job."), TimeSpan.FromMinutes(1.5)); //A fire-and-forget continuation job that has three steps BackgroundJob.ContinueJobWith( BackgroundJob.ContinueJobWith( BackgroundJob.Enqueue( () => Console.WriteLine($"Knock knock..")), () => Console.WriteLine("Who's there?")), () => Console.WriteLine("A continuation job!")); //A scheduled continuation job that has three steps BackgroundJob.ContinueJobWith( BackgroundJob.ContinueJobWith( BackgroundJob.Schedule( () => Console.WriteLine($"Knock knock.."), TimeSpan.FromMinutes(2)), () => Console.WriteLine("Who's there?")), () => Console.WriteLine("A scheduled continuation job!")); //A Cron based recurring job RecurringJob.AddOrUpdate("recurring-job-1", () => Console.WriteLine("Recurring job 1."), Cron.Minutely); //Another recurring job RecurringJob.AddOrUpdate("recurring-job-2", () => Console.WriteLine("Recurring job 2."), Cron.Minutely); //An update to the first recurring job RecurringJob.AddOrUpdate("recurring-job-1", () => Console.WriteLine("Recurring job 1 (edited)."), Cron.Minutely); Console.Read(); } }
public void Schedule <TRequest, TResult>(string name, TRequest command, string cron) where TRequest : IRequest <TResult> { RecurringJob.AddOrUpdate <BackgroundJobExecutor <TRequest, TResult> >(name, x => x.Execute(command), cron); }
public static void SetupContainer(IAppBuilder app, IUnityContainer container, IPathMapper pathMapper, string virtualRoot, string routePrefix, string modulesPhysicalPath) { container.RegisterInstance(app); var moduleInitializerOptions = (ModuleInitializerOptions)container.Resolve <IModuleInitializerOptions>(); moduleInitializerOptions.VirtualRoot = virtualRoot; moduleInitializerOptions.RoutePrefix = routePrefix; //Initialize Platform dependencies var connectionString = ConfigurationHelper.GetConnectionStringValue("VirtoCommerce"); var hangfireOptions = new HangfireOptions { StartServer = ConfigurationHelper.GetAppSettingsValue("VirtoCommerce:Jobs.Enabled", true), JobStorageType = ConfigurationHelper.GetAppSettingsValue("VirtoCommerce:Jobs.StorageType", "Memory"), DatabaseConnectionString = connectionString, }; var hangfireLauncher = new HangfireLauncher(hangfireOptions); InitializePlatform(app, container, pathMapper, connectionString, hangfireLauncher, modulesPhysicalPath); var moduleManager = container.Resolve <IModuleManager>(); var moduleCatalog = container.Resolve <IModuleCatalog>(); var applicationBase = AppDomain.CurrentDomain.SetupInformation.ApplicationBase.EnsureEndSeparator(); // Register URL rewriter for platform scripts var scriptsPhysicalPath = pathMapper.MapPath(VirtualRoot + "/Scripts").EnsureEndSeparator(); var scriptsRelativePath = MakeRelativePath(applicationBase, scriptsPhysicalPath); var platformUrlRewriterOptions = new UrlRewriterOptions(); platformUrlRewriterOptions.Items.Add(PathString.FromUriComponent("/$(Platform)/Scripts"), ""); app.Use <UrlRewriterOwinMiddleware>(platformUrlRewriterOptions); app.UseStaticFiles(new StaticFileOptions { FileSystem = new Microsoft.Owin.FileSystems.PhysicalFileSystem(scriptsRelativePath) }); // Register URL rewriter before modules initialization if (Directory.Exists(modulesPhysicalPath)) { var modulesRelativePath = MakeRelativePath(applicationBase, modulesPhysicalPath); var urlRewriterOptions = new UrlRewriterOptions(); foreach (var module in moduleCatalog.Modules.OfType <ManifestModuleInfo>()) { var urlRewriteKey = string.Format(CultureInfo.InvariantCulture, "/Modules/$({0})", module.ModuleName); var urlRewriteValue = MakeRelativePath(modulesPhysicalPath, module.FullPhysicalPath); urlRewriterOptions.Items.Add(PathString.FromUriComponent(urlRewriteKey), "/" + urlRewriteValue); moduleInitializerOptions.ModuleDirectories.Add(module.ModuleName, module.FullPhysicalPath); } app.Use <UrlRewriterOwinMiddleware>(urlRewriterOptions); app.UseStaticFiles(new StaticFileOptions { FileSystem = new Microsoft.Owin.FileSystems.PhysicalFileSystem(modulesRelativePath) }); } container.RegisterInstance(GlobalConfiguration.Configuration); // Ensure all modules are loaded foreach (var module in moduleCatalog.Modules.OfType <ManifestModuleInfo>().Where(x => x.State == ModuleState.NotStarted)) { moduleManager.LoadModule(module.ModuleName); } SwaggerConfig.RegisterRoutes(container); // Post-initialize // Register MVC areas unless running in the Web Platform Installer mode if (IsApplication) { AreaRegistration.RegisterAllAreas(); } // Register other MVC resources GlobalConfiguration.Configure(WebApiConfig.Register); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); if (IsApplication) { RouteConfig.RegisterRoutes(RouteTable.Routes); } BundleConfig.RegisterBundles(BundleTable.Bundles); AuthConfig.RegisterAuth(); // Security OWIN configuration var authenticationOptions = new Core.Security.AuthenticationOptions { CookiesEnabled = ConfigurationHelper.GetAppSettingsValue("VirtoCommerce:Authentication:Cookies.Enabled", true), CookiesValidateInterval = ConfigurationHelper.GetAppSettingsValue("VirtoCommerce:Authentication:Cookies.ValidateInterval", TimeSpan.FromDays(1)), BearerTokensEnabled = ConfigurationHelper.GetAppSettingsValue("VirtoCommerce:Authentication:BearerTokens.Enabled", true), BearerTokensExpireTimeSpan = ConfigurationHelper.GetAppSettingsValue("VirtoCommerce:Authentication:BearerTokens.AccessTokenExpireTimeSpan", TimeSpan.FromHours(1)), HmacEnabled = ConfigurationHelper.GetAppSettingsValue("VirtoCommerce:Authentication:Hmac.Enabled", true), HmacSignatureValidityPeriod = ConfigurationHelper.GetAppSettingsValue("VirtoCommerce:Authentication:Hmac.SignatureValidityPeriod", TimeSpan.FromMinutes(20)), ApiKeysEnabled = ConfigurationHelper.GetAppSettingsValue("VirtoCommerce:Authentication:ApiKeys.Enabled", true), ApiKeysHttpHeaderName = ConfigurationHelper.GetAppSettingsValue("VirtoCommerce:Authentication:ApiKeys.HttpHeaderName", "api_key"), ApiKeysQueryStringParameterName = ConfigurationHelper.GetAppSettingsValue("VirtoCommerce:Authentication:ApiKeys.QueryStringParameterName", "api_key"), }; OwinConfig.Configure(app, container, authenticationOptions); hangfireLauncher.ConfigureOwin(app, container); RecurringJob.AddOrUpdate <SendNotificationsJobs>("SendNotificationsJob", x => x.Process(), "*/1 * * * *"); var notificationManager = container.Resolve <INotificationManager>(); notificationManager.RegisterNotificationType(() => new RegistrationEmailNotification(container.Resolve <IEmailNotificationSendingGateway>()) { DisplayName = "Registration notification", Description = "This notification is sent by email to a client when he finishes registration", NotificationTemplate = new NotificationTemplate { Subject = PlatformNotificationResource.RegistrationNotificationSubject, Body = PlatformNotificationResource.RegistrationNotificationBody, Language = "en-US", } }); notificationManager.RegisterNotificationType(() => new ResetPasswordEmailNotification(container.Resolve <IEmailNotificationSendingGateway>()) { DisplayName = "Reset password notification", Description = "This notification is sent by email to a client upon reset password request", NotificationTemplate = new NotificationTemplate { Subject = PlatformNotificationResource.ResetPasswordNotificationSubject, Body = PlatformNotificationResource.ResetPasswordNotificationBody, Language = "en-US", } }); notificationManager.RegisterNotificationType(() => new TwoFactorEmailNotification(container.Resolve <IEmailNotificationSendingGateway>()) { DisplayName = "Two factor authentication", Description = "This notification contains a security token for two factor authentication", NotificationTemplate = new NotificationTemplate { Subject = PlatformNotificationResource.TwoFactorNotificationSubject, Body = PlatformNotificationResource.TwoFactorNotificationBody, Language = "en-US", } }); notificationManager.RegisterNotificationType(() => new TwoFactorSmsNotification(container.Resolve <ISmsNotificationSendingGateway>()) { DisplayName = "Two factor authentication", Description = "This notification contains a security token for two factor authentication", NotificationTemplate = new NotificationTemplate { Subject = PlatformNotificationResource.TwoFactorNotificationSubject, Body = PlatformNotificationResource.TwoFactorNotificationBody, Language = "en-US", } }); //Get initialized modules list sorted by dependency order var postInitializeModules = moduleCatalog.CompleteListWithDependencies(moduleCatalog.Modules.OfType <ManifestModuleInfo>()) .Where(m => m.ModuleInstance != null && m.State == ModuleState.Initialized) .ToArray(); foreach (var module in postInitializeModules) { moduleManager.PostInitializeModule(module); } var redisConnectionString = ConfigurationManager.ConnectionStrings["RedisConnectionString"]; // Redis if (redisConnectionString != null && !string.IsNullOrEmpty(redisConnectionString.ConnectionString)) { // Cache RedisConfigurations.AddConfiguration(new RedisConfiguration("redisConnectionString", redisConnectionString.ConnectionString)); // SignalR // https://stackoverflow.com/questions/29885470/signalr-scaleout-on-azure-rediscache-connection-issues GlobalHost.DependencyResolver.UseRedis(new RedisScaleoutConfiguration(redisConnectionString.ConnectionString, "VirtoCommerce.Platform.SignalR")); } // SignalR var tempCounterManager = new TempPerformanceCounterManager(); GlobalHost.DependencyResolver.Register(typeof(IPerformanceCounterManager), () => tempCounterManager); var hubConfiguration = new HubConfiguration { EnableJavaScriptProxies = false }; app.MapSignalR("/" + moduleInitializerOptions.RoutePrefix + "signalr", hubConfiguration); // Initialize InstrumentationKey from EnvironmentVariable var appInsightKey = Environment.GetEnvironmentVariable("APPINSIGHTS_INSTRUMENTATIONKEY"); if (!string.IsNullOrEmpty(appInsightKey)) { TelemetryConfiguration.Active.InstrumentationKey = appInsightKey; } }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, IServiceProvider serviceProvider) { IsDevelopment = env.IsDevelopment(); //app.UsePathBase("/beursspel"); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseDatabaseErrorPage(); } else { app.UseExceptionHandler("/Home/Error"); } app.UseSession(); app.UseHangfireServer(); app.UseStaticFiles(); app.UseForwardedHeaders(new ForwardedHeadersOptions { ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto }); app.UseAuthentication(); var types = Assembly.GetExecutingAssembly().GetTypes() .Where(y => typeof(IRecurringTask).IsAssignableFrom(y)); foreach (var type in types) { if (type.IsInterface) { continue; } var o = (IRecurringTask)Activator.CreateInstance(type); if (o.Enabled) { RecurringJob.AddOrUpdate(() => o.ExecuteAsync(), o.Cron, TimeZoneInfo.Local); } } app.UseMiddleware <CheckIfOpenMiddleware>(); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); var task = CreateRoles(serviceProvider); task.Wait(); var options = new DashboardOptions { Authorization = new [] { new HangfireAuthentication() } }; app.UseHangfireDashboard("/hangfire", options); using (var context = new ApplicationDbContext()) { context.Database.Migrate(); } var t1 = GeplandeTelMomentenManager.CheckMarktSluiting(); t1.Wait(); var t2 = GeplandeTelMomentenManager.CheckMarktOpening(); t2.Wait(); }
public void RemoveIfExists(string recurringJobId) { RecurringJob.RemoveIfExists(recurringJobId); }
public static void Main() { LogManager.Adapter = new ConsoleOutLoggerFactoryAdapter( LogLevel.Info, false, false, true, ""); var sqlServerStorage = new SqlServerStorage( @"Server=.\sqlexpress;Database=Hangfire.Sample;Trusted_Connection=True;"); sqlServerStorage.UseMsmqQueues(@".\Private$\hangfire{0}", "default", "critical"); JobStorage.Current = sqlServerStorage; //new RedisStorage("localhost:6379", 3); RecurringJob.AddOrUpdate(() => Console.WriteLine("Hello, world!"), Cron.Minutely); RecurringJob.AddOrUpdate("hourly", () => Console.WriteLine("Hello"), "25 15 * * *"); var options = new BackgroundJobServerOptions { Queues = new[] { "critical", "default" } }; using (var server = new BackgroundJobServer(options)) { var count = 1; while (true) { var command = Console.ReadLine(); if (command == null || command.Equals("stop", StringComparison.OrdinalIgnoreCase)) { break; } if (command.Equals("start", StringComparison.OrdinalIgnoreCase)) { server.Start(); } if (command.StartsWith("add", StringComparison.OrdinalIgnoreCase)) { try { var workCount = int.Parse(command.Substring(4)); for (var i = 0; i < workCount; i++) { var number = i; BackgroundJob.Enqueue <Services>(x => x.Random(number)); } Console.WriteLine("Jobs enqueued."); } catch (Exception ex) { Console.WriteLine(ex.Message); } } if (command.StartsWith("static", StringComparison.OrdinalIgnoreCase)) { try { var workCount = int.Parse(command.Substring(7)); for (var i = 0; i < workCount; i++) { BackgroundJob.Enqueue(() => Console.WriteLine("Hello, {0}!", "world")); } Console.WriteLine("Jobs enqueued."); } catch (Exception ex) { Console.WriteLine(ex.Message); } } if (command.StartsWith("error", StringComparison.OrdinalIgnoreCase)) { var workCount = int.Parse(command.Substring(6)); for (var i = 0; i < workCount; i++) { BackgroundJob.Enqueue <Services>(x => x.Error()); } } if (command.StartsWith("args", StringComparison.OrdinalIgnoreCase)) { var workCount = int.Parse(command.Substring(5)); for (var i = 0; i < workCount; i++) { BackgroundJob.Enqueue <Services>(x => x.Args(Guid.NewGuid().ToString(), 14442, DateTime.UtcNow)); } } if (command.StartsWith("custom", StringComparison.OrdinalIgnoreCase)) { var workCount = int.Parse(command.Substring(7)); for (var i = 0; i < workCount; i++) { BackgroundJob.Enqueue <Services>(x => x.Custom( new Random().Next(), new [] { "Hello", "world!" }, new Services.CustomObject { Id = 123 }, DayOfWeek.Friday )); } } if (command.StartsWith("fullargs", StringComparison.OrdinalIgnoreCase)) { var workCount = int.Parse(command.Substring(9)); for (var i = 0; i < workCount; i++) { BackgroundJob.Enqueue <Services>(x => x.FullArgs( false, 123, 'c', DayOfWeek.Monday, "hello", new TimeSpan(12, 13, 14), new DateTime(2012, 11, 10), new Services.CustomObject { Id = 123 }, new[] { "1", "2", "3" }, new[] { 4, 5, 6 }, new long[0], null, new List <string> { "7", "8", "9" })); } } if (command.StartsWith("in", StringComparison.OrdinalIgnoreCase)) { var seconds = int.Parse(command.Substring(2)); var number = count++; BackgroundJob.Schedule <Services>(x => x.Random(number), TimeSpan.FromSeconds(seconds)); } if (command.StartsWith("cancelable", StringComparison.OrdinalIgnoreCase)) { var iterations = int.Parse(command.Substring(11)); BackgroundJob.Enqueue <Services>(x => x.Cancelable(iterations, JobCancellationToken.Null)); } if (command.StartsWith("delete", StringComparison.OrdinalIgnoreCase)) { var workCount = int.Parse(command.Substring(7)); for (var i = 0; i < workCount; i++) { var jobId = BackgroundJob.Enqueue <Services>(x => x.EmptyDefault()); BackgroundJob.Delete(jobId); } } if (command.StartsWith("fast", StringComparison.OrdinalIgnoreCase)) { try { var workCount = int.Parse(command.Substring(5)); Parallel.For(0, workCount, i => { if (i % 2 == 0) { BackgroundJob.Enqueue <Services>(x => x.EmptyCritical()); } else { BackgroundJob.Enqueue <Services>(x => x.EmptyDefault()); } }); Console.WriteLine("Jobs enqueued."); } catch (Exception ex) { Console.WriteLine(ex.Message); } } if (command.StartsWith("generic", StringComparison.OrdinalIgnoreCase)) { BackgroundJob.Enqueue <GenericServices <string> >(x => x.Method("hello", 1)); } } } Console.WriteLine("Press Enter to exit..."); Console.ReadLine(); }
public void AddOrUpdate(Expression<Action> methodCall, Func<string> cronExpression, TimeZoneInfo timeZone = null, string queue = "default") { RecurringJob.AddOrUpdate(methodCall, cronExpression(), timeZone, queue); }
public static void AddDefaultHangfireProcesses() { RecurringJob.AddOrUpdate <MailHelper>(x => x.CleanupEmails(), "0 0 1 * *"); }
public async Task <bool> StopHomeManageAsync(string id) { var request = await this.context.Requests .Where(r => r.Id == id) .FirstOrDefaultAsync(); // Approve Request to cancel home management var result = await this.requestService.ApproveRequestAsync(id); if (result == null) { return(false); } var homeId = request.HomeId; var home = await this.context.Homes.Where(h => h.Id == homeId).FirstOrDefaultAsync(); var userId = request.UserId; var user = await this.userManager.FindByIdAsync(userId); var managedHomes = await this.context.Homes .Where(h => h.ManagerId == user.Id) .ToListAsync(); // Stop Recurring payments from Tenant to Owner List <string> transactionRequests = await this.context.TransactionRequests .Where(tr => tr.HomeId == home.Id) .Select(tr => tr.Id) .ToListAsync(); // Stop Recurring payments to Manager foreach (var transactionId in transactionRequests) { // TO DO var tr = await this.context.TransactionRequests .Where(tr => tr.Id == transactionId) .FirstOrDefaultAsync(); var payments = await this.context.Payments .Where(p => p.HomeId == home.Id) .ToListAsync(); var contract = await this.context.Contracts .Where(c => c.ManagerId == user.Id).FirstOrDefaultAsync(); this.context.Payments.RemoveRange(payments); this.context.Contracts.Remove(contract); this.context.TransactionRequests.Remove(tr); RecurringJob.RemoveIfExists(transactionId); } // Remove manager from Home and remove from role Manager if this is the only managed home if (user.ManagedHomes.Count() == 1) { home.Manager = null; await this.userManager.RemoveFromRoleAsync(user, ManagerRoleName); } else { home.Manager = null; } // Change home status home.Status = HomeStatus.ToManage; var finalResult = await this.context.SaveChangesAsync(); return(finalResult > 0); }
private void InitProcess() { var division = new Division(); RecurringJob.AddOrUpdate(() => division.DivisionRandom(), Cron.Minutely()); }
public override void Down() { RecurringJob.RemoveIfExists(nameof(MyTask)); RecurringJob.RemoveIfExists(nameof(MyTaskWithProgressBar)); }
/// <summary> /// 执行任务 /// </summary> /// <param name="serviceProvider"></param> public static void RunTask() { RecurringJob.AddOrUpdate(() => ServerLocation._iServiceProvider.Resolve <IExecuteRedisService>().ExecuteDetpthRedisJob(), Cron.Minutely()); RecurringJob.AddOrUpdate(() => ServerLocation._iServiceProvider.Resolve <IExecuteCallService>().ExecuteBalanceJob(), Cron.Daily(0), TimeZoneInfo.Local); RecurringJob.AddOrUpdate(() => ServerLocation._iServiceProvider.Resolve <IExecuteCallService>().ExecuteMarketDetailJob(), Cron.Daily(0), TimeZoneInfo.Local); }
private static void AddRecurringJob(string name, Expression <Action <IHangfireJob> > job, string cronExpression) { RecurringJob.AddOrUpdate(name, job, cronExpression); }
/// <summary> /// Adds a Hangfire task, if it doesn't already exist. /// </summary> /// <param name="jobId"> /// Hangfire task id. /// </param> /// <param name="stock"> /// Stock info /// </param> protected virtual void AddOrUpdate(string jobId, Stock stock) { RecurringJob.AddOrUpdate(jobId, () => ScheduleWatch(stock, jobId), Cron.Minutely); }
public void Post([FromBody] TaskInput input) { RecurringJob .AddOrUpdate(input.Id.ToString("D"), () => Console.WriteLine($"Task {input.Id:D}"), Cron.Minutely); }
public Task StartJob(JobConfig config) { RecurringJob.AddOrUpdate(GetId(config.Id), () => DealMsg(config), config.CronExpression); return(Task.FromResult(0)); }
public void Configuration(IAppBuilder app, string virtualRoot, string routPrefix) { VirtualRoot = virtualRoot; _assembliesPath = HostingEnvironment.MapPath(VirtualRoot + "/App_Data/Modules"); HostingEnvironment.MapPath(VirtualRoot).EnsureEndSeparator(); var modulesVirtualPath = VirtualRoot + "/Modules"; var modulesPhysicalPath = HostingEnvironment.MapPath(modulesVirtualPath).EnsureEndSeparator(); AppDomain.CurrentDomain.AssemblyResolve += CurrentDomainOnAssemblyResolve; //Modules initialization var bootstrapper = new VirtoCommercePlatformWebBootstrapper(modulesVirtualPath, modulesPhysicalPath, _assembliesPath); bootstrapper.Run(); var container = bootstrapper.Container; container.RegisterInstance(app); var moduleInitializerOptions = (ModuleInitializerOptions)container.Resolve <IModuleInitializerOptions>(); moduleInitializerOptions.VirtualRoot = virtualRoot; moduleInitializerOptions.RoutePrefix = routPrefix; //Initialize Platform dependencies const string connectionStringName = "VirtoCommerce"; var hangfireOptions = new HangfireOptions { StartServer = ConfigurationManager.AppSettings.GetValue("VirtoCommerce:Jobs.Enabled", true), JobStorageType = ConfigurationManager.AppSettings.GetValue("VirtoCommerce:Jobs.StorageType", "Memory"), DatabaseConnectionStringName = connectionStringName, }; var hangfireLauncher = new HangfireLauncher(hangfireOptions); InitializePlatform(app, container, connectionStringName, hangfireLauncher, modulesPhysicalPath); var moduleManager = container.Resolve <IModuleManager>(); var moduleCatalog = container.Resolve <IModuleCatalog>(); var applicationBase = AppDomain.CurrentDomain.SetupInformation.ApplicationBase.EnsureEndSeparator(); // Register URL rewriter for platform scripts var scriptsPhysicalPath = HostingEnvironment.MapPath(VirtualRoot + "/Scripts").EnsureEndSeparator(); var scriptsRelativePath = MakeRelativePath(applicationBase, scriptsPhysicalPath); var platformUrlRewriterOptions = new UrlRewriterOptions(); platformUrlRewriterOptions.Items.Add(PathString.FromUriComponent("/$(Platform)/Scripts"), ""); app.Use <UrlRewriterOwinMiddleware>(platformUrlRewriterOptions); app.UseStaticFiles(new StaticFileOptions { FileSystem = new Microsoft.Owin.FileSystems.PhysicalFileSystem(scriptsRelativePath) }); // Register URL rewriter before modules initialization if (Directory.Exists(modulesPhysicalPath)) { var modulesRelativePath = MakeRelativePath(applicationBase, modulesPhysicalPath); var urlRewriterOptions = new UrlRewriterOptions(); foreach (var module in moduleCatalog.Modules.OfType <ManifestModuleInfo>()) { var urlRewriteKey = string.Format(CultureInfo.InvariantCulture, "/Modules/$({0})", module.ModuleName); var urlRewriteValue = MakeRelativePath(modulesPhysicalPath, module.FullPhysicalPath); urlRewriterOptions.Items.Add(PathString.FromUriComponent(urlRewriteKey), "/" + urlRewriteValue); moduleInitializerOptions.ModuleDirectories.Add(module.ModuleName, module.FullPhysicalPath); } app.Use <UrlRewriterOwinMiddleware>(urlRewriterOptions); app.UseStaticFiles(new StaticFileOptions { FileSystem = new Microsoft.Owin.FileSystems.PhysicalFileSystem(modulesRelativePath) }); } container.RegisterInstance(GlobalConfiguration.Configuration); // Ensure all modules are loaded foreach (var module in moduleCatalog.Modules.OfType <ManifestModuleInfo>().Where(x => x.State == ModuleState.NotStarted)) { moduleManager.LoadModule(module.ModuleName); } SwaggerConfig.RegisterRoutes(container); // Post-initialize // Platform MVC configuration if (IsApplication) { AreaRegistration.RegisterAllAreas(); } GlobalConfiguration.Configure(WebApiConfig.Register); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); AuthConfig.RegisterAuth(); // Security OWIN configuration var authenticationOptions = new Core.Security.AuthenticationOptions { CookiesEnabled = ConfigurationManager.AppSettings.GetValue("VirtoCommerce:Authentication:Cookies.Enabled", true), CookiesValidateInterval = ConfigurationManager.AppSettings.GetValue("VirtoCommerce:Authentication:Cookies.ValidateInterval", TimeSpan.FromDays(1)), BearerTokensEnabled = ConfigurationManager.AppSettings.GetValue("VirtoCommerce:Authentication:BearerTokens.Enabled", true), BearerTokensExpireTimeSpan = ConfigurationManager.AppSettings.GetValue("VirtoCommerce:Authentication:BearerTokens.AccessTokenExpireTimeSpan", TimeSpan.FromHours(1)), HmacEnabled = ConfigurationManager.AppSettings.GetValue("VirtoCommerce:Authentication:Hmac.Enabled", true), HmacSignatureValidityPeriod = ConfigurationManager.AppSettings.GetValue("VirtoCommerce:Authentication:Hmac.SignatureValidityPeriod", TimeSpan.FromMinutes(20)), ApiKeysEnabled = ConfigurationManager.AppSettings.GetValue("VirtoCommerce:Authentication:ApiKeys.Enabled", true), ApiKeysHttpHeaderName = ConfigurationManager.AppSettings.GetValue("VirtoCommerce:Authentication:ApiKeys.HttpHeaderName", "api_key"), ApiKeysQueryStringParameterName = ConfigurationManager.AppSettings.GetValue("VirtoCommerce:Authentication:ApiKeys.QueryStringParameterName", "api_key"), }; OwinConfig.Configure(app, container, authenticationOptions); hangfireLauncher.ConfigureOwin(app, container); RecurringJob.AddOrUpdate <SendNotificationsJobs>("SendNotificationsJob", x => x.Process(), "*/1 * * * *"); var notificationManager = container.Resolve <INotificationManager>(); notificationManager.RegisterNotificationType(() => new RegistrationEmailNotification(container.Resolve <IEmailNotificationSendingGateway>()) { DisplayName = "Registration notification", Description = "This notification sends by email to client when he finish registration", NotificationTemplate = new NotificationTemplate { Body = PlatformNotificationResource.RegistrationNotificationBody, Subject = PlatformNotificationResource.RegistrationNotificationSubject } }); notificationManager.RegisterNotificationType(() => new ResetPasswordEmailNotification(container.Resolve <IEmailNotificationSendingGateway>()) { DisplayName = "Reset password notification", Description = "This notification sends by email to client when he want to reset his password", NotificationTemplate = new NotificationTemplate { Body = PlatformNotificationResource.ResetPasswordNotificationBody, Subject = PlatformNotificationResource.ResetPasswordNotificationSubject } }); var postInitializeModules = moduleCatalog.CompleteListWithDependencies(moduleCatalog.Modules.OfType <ManifestModuleInfo>()) .Where(m => m.ModuleInstance != null) .ToArray(); foreach (var module in postInitializeModules) { moduleManager.PostInitializeModule(module); } // SignalR var tempCounterManager = new TempPerformanceCounterManager(); GlobalHost.DependencyResolver.Register(typeof(IPerformanceCounterManager), () => tempCounterManager); var hubConfiguration = new HubConfiguration { EnableJavaScriptProxies = false }; app.MapSignalR("/" + moduleInitializerOptions.RoutePrefix + "signalr", hubConfiguration); // Initialize InstrumentationKey from EnvironmentVariable("APPINSIGHTS_INSTRUMENTATIONKEY") var appInsightKey = Environment.GetEnvironmentVariable("APPINSIGHTS_INSTRUMENTATIONKEY"); if (!string.IsNullOrEmpty(appInsightKey)) { TelemetryConfiguration.Active.InstrumentationKey = appInsightKey; } }
public void ScheduleRecurring <T>(string taskName, Expression <Action <T> > task, string cronExpression) { RecurringJob.AddOrUpdate(taskName, task, cronExpression); }
public static void UseHangfireTest(this IServiceProvider service) { var job = service.GetService <HangfireTestJob>(); RecurringJob.AddOrUpdate("定时任务测试", () => job.ExecuteAsync(), CronType.Minute()); }