/// <summary> /// 简单测试 /// </summary> static void SimpleTest(int counter) { var client = new BackgroundJobClient(); var jobId = client.Enqueue(() => SomeMethod(0)); var jobId1 = client.Enqueue(() => SomeMethod1(0)); var jobId2 = client.Enqueue(() => SomeMethod2(0)); var jobId3 = client.Enqueue(() => SomeMethod3(0)); var jobId4 = client.Enqueue(() => SomeMethod4(0)); var jobId5 = client.Enqueue(() => SomeMethod5(0)); var jobId6 = client.Enqueue(() => SomeMethod6(0)); var jobId7 = client.Enqueue(() => SomeMethod7(0)); var jobId8 = client.Enqueue(() => SomeMethod8(0)); var jobId9 = client.Enqueue(() => SomeMethod9(0)); for (int i = 1; i < counter; i++) { jobId = client.ContinueWith(jobId, () => SomeMethod(i)); //Thread.Sleep(1000); jobId1 = client.ContinueWith(jobId1, () => SomeMethod1(i)); jobId2 = client.ContinueWith(jobId2, () => SomeMethod2(i)); //jobId3 = client.ContinueWith(jobId3, () => SomeMethod3(i)); client.Enqueue(() => SomeMethod3(i)); jobId4 = client.ContinueWith(jobId4, () => SomeMethod4(i)); jobId5 = client.ContinueWith(jobId5, () => SomeMethod5(i)); jobId6 = client.ContinueWith(jobId6, () => SomeMethod6(i)); jobId7 = client.ContinueWith(jobId7, () => SomeMethod7(i)); jobId8 = client.ContinueWith(jobId8, () => SomeMethod8(i)); jobId9 = client.ContinueWith(jobId9, () => SomeMethod9(i)); } }
public static void SetTrigger(this IStorageConnection connection, string triggerName) { var jsc = (JobStorageConnection)connection; var client = new BackgroundJobClient(); SetTriggerInternal(client, jsc, triggerName); }
public void HangfireScheduler_ResumeJob_InSucceededState_Failed() { var dataObjectMock = new Mock <IDSFDataObject>(); var values = new Dictionary <string, StringBuilder> { { "resourceID", new StringBuilder("ab04663e-1e09-4338-8f61-a06a7ae5ebab") }, { "environment", new StringBuilder("NewEnvironment") }, { "startActivityId", new StringBuilder("4032a11e-4fb3-4208-af48-b92a0602ab4b") }, { "versionNumber", new StringBuilder("1") }, { "currentuserprincipal", new StringBuilder(WindowsIdentity.GetCurrent().Name) } }; var jobstorage = new MemoryStorage(); var client = new BackgroundJobClient(jobstorage); var scheduler = new Persistence.Drivers.HangfireScheduler(client, jobstorage); var jobId = scheduler.ScheduleJob(enSuspendOption.SuspendForSeconds, "1", values); var o = new object(); var state = new SucceededState(o, 1, 1); client.ChangeState(jobId, state, ScheduledState.StateName); var result = scheduler.ResumeJob(dataObjectMock.Object, jobId, false, "NewEnvironment"); Assert.AreEqual(GlobalConstants.Failed, result); }
private void QueueMpi(SendManifestPackageDTO package) { var client = new BackgroundJobClient(); var state = new EnqueuedState("mpi"); client.Create(() => _cbsSendService.SendMpiAsync(package), state); }
public void CreateWorkflow2() { var dl = WorkflowJob.MakeJob(() => WorkflowMethod("Download")); var co1 = WorkflowJob.MakeJob(() => FailingWorkflowMethod("Do something 1"), maxRetries: 1); var co2 = WorkflowJob.MakeJob(() => WorkflowMethod("Do something 2")); var co3 = WorkflowJob.MakeJob(() => WorkflowMethod("Do something 3")); var se1 = WorkflowJob.MakeJob(() => WorkflowMethod("Send email 1")); var se3 = WorkflowJob.MakeJob(() => WorkflowMethod("Send email 3")); var de = WorkflowJob.MakeJob(() => WorkflowMethod("Delete email")); de.WaitFor(se1, co2, se3); co1.ContinueWith(se1); co3.ContinueWith(se3); var group = WorkflowJobGroup.RunInParallel(co1, co2, co3); dl.ContinueWithGroup(group); var wf = new Workflow(dl); GlobalConfiguration.Configuration.UseSqlServerStorage("db"); var client = new BackgroundJobClient(); client.CreateAndEnqueue(wf); }
public void Load() { var config = BackgroundJobClient.GetConfig(); HubUrl = config.HubUrl; Location = config.Location; }
// forceEmail set to false sends notification with no email. Set forceEmail to null to not force either way public async Task SendNotificationToUserAsync(User user, String messageId, Dictionary <string, object> subs, String linkUrl = "", bool?forceEmail = null, bool sendEmailImmediately = false) { var locale = user.LocaleOrDefault(); var fullMessageId = "notifications.notification." + messageId; var translated = await Translator.TranslateAsync(locale, "notifications", fullMessageId, subs); translated = HttpUtility.HtmlDecode(translated); var sendEmail = !user.EmailNotification.HasValue || user.EmailNotification.Value; if (forceEmail.HasValue) { sendEmail = forceEmail.Value; } var notification = new Notification { UserId = user.Id, Message = translated, SendEmail = sendEmail, MessageSubstitutions = subs, MessageId = messageId, LinkUrl = linkUrl }; var updatedNotification = await NotificationRepository.CreateAsync(notification); if (sendEmailImmediately) { BackgroundJobClient.Enqueue <SendNotificationService>(service => service.SendEmailNotificationImmediate(updatedNotification.Id)); } }
public async Task <IActionResult> WebhookCallback([FromBody] JObject body) { // catch any errors, we don't want to return 500 try { string eventType = body["hook"]["event"].ToString(); string userId = body["hook"]["createdBy"].ToString(); string projectId = "b." + body["payload"]["project"].ToString();//body["hook"]["hookAttribute"]["projectId"].ToString(); string versionId = body["resourceUrn"].ToString(); string hubId = "b." + body["payload"]["tenant"].ToString(); string fileName = body["payload"]["name"].ToString(); string extension = fileName.Split(".").Last(); string folderUrn = body["hook"]["tenant"].ToString(); string itemUrn = body["payload"]["lineageUrn"].ToString(); // do you want to filter events?? if (eventType != "dm.version.added") { return(Ok()); } if (Config.SupportedFormats.IndexOf(extension) == -1) { return(Ok()); } // use Hangfire to schedule a job BackgroundJobClient metadataQueue = new BackgroundJobClient(); IState state = new EnqueuedState("metadata"); metadataQueue.Create(() => ModelDerivativeController.ProcessFileAsync(userId, hubId, projectId, folderUrn, itemUrn, versionId, fileName, null), state); } catch { } // ALWAYS return ok (200) return(Ok()); }
public ActionResult UpdateBlogs(FormCollection fc) { #region 验证用户信息 string _SessionId = HttpContext.Request.Cookies["SessionId"].Value; string _UserProfileJson = RedisHelper.ItemGet <string>(_SessionId); #endregion var _Content = fc["editor"]; var _BlogsId = fc["BlogsId"]; if (!string.IsNullOrEmpty(_UserProfileJson)) { UserProfile _UserProfile = ToolMethod.GetUerProfile(_UserProfileJson); BlogsInfo _BlogsInfo = _IBlogsInfoBLL.GetModels(x => x.Id == _BlogsId && x.Delflag == EnumType.DelflagType.正常, true, null, "BlogsInfo").FirstOrDefault(); _BlogsInfo.BlogContent = _Content; _BlogsInfo.UDate = ToolMethod.GetNow(); RedisHelper.HashSet <BlogsInfo>("BlogsInfo", _BlogsId, _BlogsInfo); BackgroundJobClient _Job = new BackgroundJobClient(); _Job.Enqueue(() => _IBlogsInfoBLL.Update(_BlogsInfo)); return(Json(new { Success = true, SuccessModel = "修改博客成功!" })); } else { return(RedirectToAction("Login", "Account")); } }
public static async Task Main(string[] args) { var config = new ConfigurationBuilder() .AddEnvironmentVariables() .SetBasePath(PlatformServices.Default.Application.ApplicationBasePath) .AddJsonFile($"appsettings.{Environment.UserName}.json", true) .AddJsonFile("appsettings.Development.json", true) .AddJsonFile("appsettings.json") .Build(); var serviceProvider = BootstrapDependencyInjection(config); var hangfireOptions = serviceProvider.GetHangfireOptionsOrDefault(); var hangfireJobStorage = CreateRedisJobStorage(hangfireOptions); using (var server = CreateHangfireBackgroundJobServer(hangfireJobStorage, new HangfireActivator(serviceProvider))) { var smtpOptions = serviceProvider.GetSmtpOptionsOrDefault(); var backgroundJobClient = new BackgroundJobClient(hangfireJobStorage); var options = new OptionsBuilder() .ServerName(smtpOptions.HostName) .Port(smtpOptions.Port) .MessageStore(new RedisMinioMailStore(backgroundJobClient)) .Build(); var smtpServer = new SmtpServer.SmtpServer(options); await smtpServer.StartAsync(CancellationToken.None); server.SendStop(); } }
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结束程序!"); } } } }
private async Task GetItemVersionsAsync(Credentials credentials, string hubId, string folderUrn, string itemHref, PerformContext context) { await credentials.RefreshAsync(); BackgroundJobClient metadataQueue = new BackgroundJobClient(); IState state = new EnqueuedState("metadata"); // the API SDK ItemsApi itemApi = new ItemsApi(); itemApi.Configuration.AccessToken = credentials.TokenInternal; // extract the projectId & itemId from the href string[] idParams = itemHref.Split('/'); string itemUrn = idParams[idParams.Length - 1]; string projectId = idParams[idParams.Length - 3]; var item = await itemApi.GetItemAsync(projectId, itemUrn); string versionUrn = (string)item.data.relationships.tip.data.id; string fileName = (string)item.data.attributes.displayName; string extension = fileName.Split(".").Last().ToLower(); if (Config.SupportedFormats.IndexOf(extension) == -1) { return; } string absolutePath = string.Format("/manifest/_doc/{0}", ModelDerivativeController.Base64Encode(itemUrn)); RestClient client = new RestClient(Config.ElasticSearchServer); RestRequest request = new RestRequest(absolutePath, RestSharp.Method.GET); if (!string.IsNullOrEmpty(Config.AWSKey) && !string.IsNullOrEmpty(Config.AWSSecret)) { SortedDictionary <string, string> headers = AWS.Signature.SignatureHeader( Amazon.RegionEndpoint.GetBySystemName(Config.AWSRegion), new Uri(Config.ElasticSearchServer).Host, "GET", string.Empty, absolutePath); foreach (var entry in headers) { request.AddHeader(entry.Key, entry.Value); } } IRestResponse res = await client.ExecuteTaskAsync(request); if (res.StatusCode == HttpStatusCode.OK && Config.SkipAlreadyIndexed) { context.WriteLine(string.Format("{0}: already indexed, skip", fileName)); System.Threading.Thread.Sleep(1000); // otherwise we'll reach the rate limit... return; } context.WriteLine(string.Format("{0}: {1}", fileName, versionUrn)); await ModelDerivativeHub.NotifyFileFound(_hubContext, hubId); metadataQueue.Create(() => ProcessFile(credentials.UserId, hubId, projectId, folderUrn, itemUrn, versionUrn, fileName, null), state); }
private static Task Producer( ILoggerFactory loggerFactory, JobStorage storage, CancellationToken token) { var logger = loggerFactory.CreateLogger("main"); var counter = 0; var client = new BackgroundJobClient(storage); void Create() { while (!token.IsCancellationRequested) { var i = Interlocked.Increment(ref counter); try { client.Schedule(() => HandleJob(i), DateTimeOffset.UtcNow); Ticks.OnNext(Unit.Default); } catch (Exception e) { logger.LogError(e, "Scheduling failed"); } } } return(Task.WhenAll( Task.Run(Create, token), Task.Run(Create, token), Task.Run(Create, token), Task.Run(Create, token))); }
public Client() { var entry = GlobalConfiguration.Configuration.UseSqlServerStorage(ConectionString); var current = entry.Entry; var states = current.GetMonitoringApi(); List <RecurringJobDto> recurringJobs = JobStorage.Current.GetConnection().GetRecurringJobs(); recurringJobs.ForEach(x => Console.WriteLine(x.Id)); hfClient = new BackgroundJobClient(current); CreateJob(); //var jobId = BackgroundJob.Enqueue(() => Console.WriteLine("Pozdrav z klienta !")); //var jobId2 = hfClient.ContinueWith(jobId, () => Console.WriteLine("Následuje po pozdravu z klienta !")); ////var job = new Hangfire.Common.Job(() => Console.WriteLine("Pozdrav z klienta !")); //Console.WriteLine($"jobId={jobId},jobId2={jobId2}"); //System.Threading.Thread.Sleep(2000); //Console.WriteLine(hfClient.RetryAttempts); //if (hfClient.Delete(jobId, "Succeeded")) // Console.WriteLine($"Succeeded deleted {jobId}"); var monitoringApi = JobStorage.Current.GetMonitoringApi(); var deletedJobs = monitoringApi.DeletedJobs(0, 10); // If no queue name was defined somewhere, probably this will be "default". // If no items have been queued, then the queue won't exist, and it will error here. var queue = monitoringApi.Queues().First().Name; var enqueudjobs = monitoringApi.SucceededJobs(0, 10); enqueudjobs.ForEach(x => hfClient.Delete(x.Key)); }
private static void HandleInput(ConsoleKeyInfo input) { /*if (input.KeyChar.Equals('s')) * { * * * var newInput = Console.ReadKey(); * HandleInput(newInput); * } * else*/if (input.KeyChar.Equals('q')) { BackgroundJobClient c = new BackgroundJobClient(_storage); //RecurringJob.AddOrUpdate(()=>MyJob.DoSomething(),Cron. var b = new BackgroundJobClient(_storage); //b.Enqueue(() => Console.WriteLine("my job")); c.Enqueue(() => LaunchAppJob.Launch(@"C:\TFSDATA\KissTheFuture\Trunk\shopping.lacage.be\shoppingconsole.lacage.be\bin\Debug\shoppingconsole.lacage.be.exe"));//, new Hangfire.States.EnqueuedState("backgroundsynchro")); //c.Enqueue(() => Console.Write('q')); Console.WriteLine("Hangfire job enqueued. Press any key to exit..."); //Thread.Sleep(5000); var newInput = Console.ReadKey(); HandleInput(newInput); } }
public ActionResult ChooseRolePermission(string RolePermissionId) { try { if (string.IsNullOrEmpty(RolePermissionId)) { return(Json(new { Success = false, ErrorMessage = "角色权限关系ID不能为空" })); } RolePermission _rolePermission = _IRolePermissionBLL.GetModels(x => x.Delflag == EnumType.DelflagType.正常 && x.Id == RolePermissionId, true, x => x.Delflag == EnumType.DelflagType.正常, "RolePermission").FirstOrDefault(); if (_rolePermission.UsedType == EnumType.UsedType.启用) { _rolePermission.UsedType = EnumType.UsedType.未启用; } else { _rolePermission.UsedType = EnumType.UsedType.启用; } //更新缓存 _IRolePermissionBLL.UpdateCache("RolePermission", _rolePermission.Id, _rolePermission); //异步更新数据库 BackgroundJobClient _jobs = new BackgroundJobClient(); _jobs.Enqueue(() => _IRolePermissionBLL.Update(_rolePermission)); return(Json(new { Success = true, SuccessModel = "选中关系生效!" })); } catch (Exception ee) { return(Json(new { Success = false, ErrorMessage = ee.ToString() })); } }
public async Task ProductActivityChangedAsync(ProductActivityChangedArgs args) { using (var scope = ServiceProvider.CreateScope()) { // Find the Product assoicated with the ProcessId var product = await ProductRepository.Get() .Where(p => p.Id == args.ProcessId) .Include(p => p.ProductDefinition) .Include(p => p.Project) .ThenInclude(pr => pr.Owner) .FirstOrDefaultAsync(); if (product == null) { Log.Error($"Could find Product for ProcessId={args.ProcessId}"); return; } var comment = await ReassignUserTasksForProduct(product); if (args.TransitionType == TransitionType.Rejection) { BackgroundJobClient.Enqueue <SendEmailService>(service => service.SendRejectEmail(product.Id, args, comment)); } } }
static void Main(string[] args) { try { for (int i = 0; i < args.Length; i++) { if (args[i] == "-h") { PrintHelp(); } else if (args[i] == "-host") { if (i++ < args.Length) { Console.WriteLine($"Using host: {args[i]}"); BackgroundJobClient.JobUrl = $"http://{args[i]}:8888/api"; } else { Console.WriteLine("Missing argument for host"); break; } } else if (args[i] == "-view-config") { var config = BackgroundJobClient.GetConfig(); Console.WriteLine(config); } else if (args[i] == "-view-data") { PrintOverviewData(BackgroundJobClient.GetOverviewData()); Console.WriteLine(); PrintSensorData(BackgroundJobClient.GetMeasuredData()); } else if (args[i] == "-set-location") { if (i++ < args.Length) { Console.WriteLine($"Using location: {args[i]}"); var config = BackgroundJobClient.GetConfig(); config.Location = args[i]; BackgroundJobClient.UpdateConfig(config); } else { Console.WriteLine("Missing argument for location"); break; } } } } catch (Exception ex) { Console.WriteLine(ex); } if (args.Length == 0) { PrintHelp(); } }
public static string CreateJob(Expression <Action> methodCall, string queueName) { var queue = new Hangfire.States.EnqueuedState(queueName); var job = Hangfire.Common.Job.FromExpression(methodCall); var jobId = new BackgroundJobClient().Create(job, queue); return(jobId); }
private static void CreateStartUpJobs(JobBuilderOptions builderOptions) { var jobManager = new BackgroundJobClient(JobStorage.Current); builderOptions.JsonFileLocations.Select(GetFileContents) .SelectMany(JsonConvert.DeserializeObject <List <JobInfo> >) .ForEach(x => CreateStartUpJob(x, jobManager)); }
public void ApplyWatermark(string picture) { //IFileSystemStorage storage = new FileSystemStorage(); var client = new BackgroundJobClient(); // client.Create() client.Enqueue <IFileSystemStorage>(file => file.ApplyWatermark(picture)); }
public HttpResponseMessage Post() { var client = new BackgroundJobClient(); var test = "test param"; client.Enqueue(() => CallApi(test)); return(Request.CreateResponse(HttpStatusCode.Created)); }
private static void Main(string[] args) { var storage = new SqlServerStorage( "Server=(localdb)\\MSSQLLocalDB;Initial Catalog=HostFun;MultipleActiveResultSets=True"); var client = new BackgroundJobClient(storage); client.Enqueue <IGreeter>(greeter => greeter.Greet()); }
public ActionResult QueueServerBJob2(Default1Model model) { var jobClient = new BackgroundJobClient(); var jobId = jobClient.Enqueue(() => BackgroundJobs.QueueServerBJob2()); model.ServerBJob2Id = jobId; return(View("Index", model)); }
public void CreateInEnqueuedState() { #region EnqueuedState #1 var client = new BackgroundJobClient(); var state = new EnqueuedState("critical"); // Use the "critical" queue client.Create(() => Console.WriteLine("Hello!"), state); #endregion }
public void 集成測試() { var job = new DemoJob(); var client = new BackgroundJobClient(); job.JobClient = client; job.EnqueueAction(); Thread.Sleep(5000); }
public void CreateInScheduledState() { #region ScheduledState var client = new BackgroundJobClient(); var state = new ScheduledState(TimeSpan.FromHours(2)); client.Create(() => Console.WriteLine("Hello!"), state); #endregion }
public void HangfireScheduler_ResumeJob_WorkflowResumeReturnsErrors_Failed() { var mockStateNotifier = new Mock <IStateNotifier>(); mockStateNotifier.Setup(o => o.LogAdditionalDetail(It.IsAny <Audit>(), "ResumeJob")).Verifiable(); var mockPrincipal = new Mock <IPrincipal>(); mockPrincipal.Setup(o => o.Identity).Returns(WindowsIdentity.GetCurrent()); var dataObjectMock = new Mock <IDSFDataObject>(); dataObjectMock.Setup(o => o.StateNotifier).Returns(mockStateNotifier.Object); dataObjectMock.Setup(o => o.ExecutingUser).Returns(mockPrincipal.Object); var values = new Dictionary <string, StringBuilder> { { "resourceID", new StringBuilder("ab04663e-1e09-4338-8f61-a06a7ae5ebab") }, { "environment", new StringBuilder("NewEnvironment") }, { "startActivityId", new StringBuilder("4032a11e-4fb3-4208-af48-b92a0602ab4b") }, { "versionNumber", new StringBuilder("1") }, { "currentuserprincipal", new StringBuilder(WindowsIdentity.GetCurrent().Name) } }; var suspendOption = enSuspendOption.SuspendUntil; var suspendOptionValue = DateTime.Now.AddDays(1).ToString(); var jobstorage = new MemoryStorage(); var client = new BackgroundJobClient(jobstorage); var scheduler = new Persistence.Drivers.HangfireScheduler(client, jobstorage); var jobId = scheduler.ScheduleJob(suspendOption, suspendOptionValue, values); var errors = new ErrorResultTO(); errors.AddError("ErrorMessage"); var resourceCatalog = new Mock <IResourceCatalog>(); resourceCatalog.Setup(catalog => catalog.GetService(GlobalConstants.ServerWorkspaceID, It.IsAny <Guid>(), "")).Returns(CreateServiceEntry()); CustomContainer.Register(resourceCatalog.Object); var mockResumableExecutionContainer = new Mock <IResumableExecutionContainer>(); mockResumableExecutionContainer.Setup(o => o.Execute(out errors, 0)).Verifiable(); var mockResumableExecutionContainerFactory = new Mock <IResumableExecutionContainerFactory>(); mockResumableExecutionContainerFactory.Setup(o => o.New(It.IsAny <Guid>(), It.IsAny <ServiceAction>(), It.IsAny <DsfDataObject>())) .Returns(mockResumableExecutionContainer.Object); CustomContainer.Register(mockResumableExecutionContainerFactory.Object); var result = scheduler.ResumeJob(dataObjectMock.Object, jobId, false, "NewEnvironment"); Assert.AreEqual(GlobalConstants.Failed, result); mockResumableExecutionContainer.Verify(o => o.Execute(out errors, 0), Times.Once); }
public EngineServiceTestEnvironment() { EngineRepository = new MemoryEngineRepository(); BuildRepository = new MemoryBuildRepository(); ProjectRepository = new MemoryProjectRepository(); EngineOptions = new EngineOptions(); _memoryStorage = new MemoryStorage(); _jobClient = new BackgroundJobClient(_memoryStorage); }
public TenantedBackgroundJobClient(TraffkGlobalDbContext gdb, ITraffkTenantFinder finder, IJobInfoFinder jobInfoFinder = null, ICurrentUser currentUser = null) { Inner = new BackgroundJobClient(); GDB = gdb; Finder = finder; CurrentUser = currentUser; RecurringJobManager = new RecurringJobManager(); TenantId = Finder.GetTenantIdAsync().ExecuteSynchronously(); JobInfoFinder = jobInfoFinder; }
public static void AddClientBatchCommand( this RouteCollection routes, string pathTemplate, [NotNull] Action<IBackgroundJobClient, string> command) { if (command == null) throw new ArgumentNullException("command"); routes.AddBatchCommand(pathTemplate, (context, jobId) => { var client = new BackgroundJobClient(context.JobStorage); command(client, jobId); }); }
public void GivenAClient() { _client = new BackgroundJobClient( Redis.Storage, new JobCreationProcess(_filters)); }
static DashboardRoutes() { Routes = new RouteCollection(); Routes.AddRazorPage("/", x => new HomePage()); Routes.Add("/stats", new JsonStats()); #region Embedded static content Routes.Add("/js[0-9]{3}", new CombinedResourceDispatcher( "application/javascript", GetExecutingAssembly(), GetContentFolderNamespace("js"), Javascripts)); Routes.Add("/css[0-9]{3}", new CombinedResourceDispatcher( "text/css", GetExecutingAssembly(), GetContentFolderNamespace("css"), Stylesheets)); Routes.Add("/fonts/glyphicons-halflings-regular/eot", new EmbeddedResourceDispatcher( "application/vnd.ms-fontobject", GetExecutingAssembly(), GetContentResourceName("fonts", "glyphicons-halflings-regular.eot"))); Routes.Add("/fonts/glyphicons-halflings-regular/svg", new EmbeddedResourceDispatcher( "image/svg+xml", GetExecutingAssembly(), GetContentResourceName("fonts", "glyphicons-halflings-regular.svg"))); Routes.Add("/fonts/glyphicons-halflings-regular/ttf", new EmbeddedResourceDispatcher( "application/octet-stream", GetExecutingAssembly(), GetContentResourceName("fonts", "glyphicons-halflings-regular.ttf"))); Routes.Add("/fonts/glyphicons-halflings-regular/woff", new EmbeddedResourceDispatcher( "font/woff", GetExecutingAssembly(), GetContentResourceName("fonts", "glyphicons-halflings-regular.woff"))); Routes.Add("/fonts/glyphicons-halflings-regular/woff2", new EmbeddedResourceDispatcher( "font/woff2", GetExecutingAssembly(), GetContentResourceName("fonts", "glyphicons-halflings-regular.woff2"))); #endregion #region Razor pages and commands Routes.AddRazorPage("/jobs/enqueued", x => new QueuesPage()); Routes.AddRazorPage( "/jobs/enqueued/fetched/(?<Queue>.+)", x => new FetchedJobsPage(x.Groups["Queue"].Value)); Routes.AddClientBatchCommand("/jobs/enqueued/delete", (client, jobId) => client.ChangeState(jobId, CreateDeletedState())); Routes.AddClientBatchCommand("/jobs/enqueued/requeue", (client, jobId) => client.ChangeState(jobId, CreateEnqueuedState())); Routes.AddRazorPage( "/jobs/enqueued/(?<Queue>.+)", x => new EnqueuedJobsPage(x.Groups["Queue"].Value)); Routes.AddRazorPage("/jobs/processing", x => new ProcessingJobsPage()); Routes.AddClientBatchCommand( "/jobs/processing/delete", (client, jobId) => client.ChangeState(jobId, CreateDeletedState(), ProcessingState.StateName)); Routes.AddClientBatchCommand( "/jobs/processing/requeue", (client, jobId) => client.ChangeState(jobId, CreateEnqueuedState(), ProcessingState.StateName)); Routes.AddRazorPage("/jobs/scheduled", x => new ScheduledJobsPage()); Routes.AddClientBatchCommand( "/jobs/scheduled/enqueue", (client, jobId) => client.ChangeState(jobId, CreateEnqueuedState(), ScheduledState.StateName)); Routes.AddClientBatchCommand( "/jobs/scheduled/delete", (client, jobId) => client.ChangeState(jobId, CreateDeletedState(), ScheduledState.StateName)); Routes.AddRazorPage("/jobs/succeeded", x => new SucceededJobs()); Routes.AddClientBatchCommand( "/jobs/succeeded/requeue", (client, jobId) => client.ChangeState(jobId, CreateEnqueuedState(), SucceededState.StateName)); Routes.AddRazorPage("/jobs/failed", x => new FailedJobsPage()); Routes.AddClientBatchCommand( "/jobs/failed/requeue", (client, jobId) => client.ChangeState(jobId, CreateEnqueuedState(), FailedState.StateName)); Routes.AddClientBatchCommand( "/jobs/failed/delete", (client, jobId) => client.ChangeState(jobId, CreateDeletedState(), FailedState.StateName)); Routes.AddRazorPage("/jobs/deleted", x => new DeletedJobsPage()); Routes.AddClientBatchCommand( "/jobs/deleted/requeue", (client, jobId) => client.ChangeState(jobId, CreateEnqueuedState(), DeletedState.StateName)); Routes.AddRazorPage("/jobs/awaiting", x => new AwaitingJobsPage()); Routes.AddClientBatchCommand("/jobs/awaiting/enqueue", (client, jobId) => client.ChangeState( jobId, CreateEnqueuedState(), AwaitingState.StateName)); Routes.AddClientBatchCommand("/jobs/awaiting/delete", (client, jobId) => client.ChangeState( jobId, CreateDeletedState(), AwaitingState.StateName)); Routes.AddCommand( "/jobs/actions/requeue/(?<JobId>.+)", context => { var client = new BackgroundJobClient(context.Storage); return client.ChangeState(context.UriMatch.Groups["JobId"].Value, CreateEnqueuedState()); }); Routes.AddCommand( "/jobs/actions/delete/(?<JobId>.+)", context => { var client = new BackgroundJobClient(context.Storage); return client.ChangeState(context.UriMatch.Groups["JobId"].Value, CreateDeletedState()); }); Routes.AddRazorPage("/jobs/details/(?<JobId>.+)", x => new JobDetailsPage(x.Groups["JobId"].Value)); Routes.AddRazorPage("/recurring", x => new RecurringJobsPage()); Routes.AddRecurringBatchCommand( "/recurring/remove", (manager, jobId) => manager.RemoveIfExists(jobId)); Routes.AddRecurringBatchCommand( "/recurring/trigger", (manager, jobId) => manager.Trigger(jobId)); Routes.AddRazorPage("/servers", x => new ServersPage()); Routes.AddRazorPage("/retries", x => new RetriesPage()); #endregion }