/// <summary> /// Create background jobs to populate users and sandboxes /// This class separates the initialization engine from HangFire /// </summary> public void Configure() { if (!_initializationModel.Enabled) { return; } if (_apiConfigurationProvider.DatabaseEngine == DatabaseEngine.SqlServer) { // initial creation of roles, users, and sandboxes at server startup for sql server only var id1 = BackgroundJob.Enqueue(() => _engine.CreateIdentityRoles()); BackgroundJob.ContinueJobWith(id1, () => _engine.CreateIdentityUsers()); } // add vendors and sandboxes var id2 = BackgroundJob.Enqueue(() => _engine.CreateVendors()); var id3 = BackgroundJob.ContinueJobWith(id2, () => _engine.CreateSandboxes()); BackgroundJob.ContinueJobWith(id3, () => _engine.UpdateClientWithLEAIdsFromPopulatedSandbox()); // refresh existing sandboxes periodically if (_initializationModel.Users.Any(u => u.Sandboxes.Any(s => s.Refresh))) { // Change the recurrence to suit your needs using Cron functions or a unix CRON expressions (i.e. "* */6 * * *" = every 6 hours) RecurringJob.AddOrUpdate("RebuildSandboxes", () => _engine.RebuildSandboxes(), Cron.Daily(), TimeZoneInfo.Local); } }
public ActionResult Index() { var id = _userService.GetCurrentUserId(); IEnumerable <Trip> objList = _repositoryTrip.GetWithIncludeByUserId(id); if (objList.Any()) { var trip = objList.First(); using (var connection = JobStorage.Current.GetConnection()) { foreach (var recurringJob in connection.GetRecurringJobs()) { RecurringJob.RemoveIfExists(recurringJob.Id); } } var timeDelay = (trip.TimeBeforeDeparture.ApproximateStart - _utilService.DateTimeNow()).Value; var idJob = BackgroundJob.Schedule(() => _tripService.ToHistory(trip.Id), timeDelay); BackgroundJob.ContinueJobWith( idJob, () => Response.Redirect(HttpContext.Request.Path)); BackgroundJob.Schedule(() => Response.Redirect(Request.Path), timeDelay); } return(View(objList)); }
public async Task <bool> ProcessEntryFromUploadFile( Guid entryId, string audioUrl, string authToken, PerformContext context) { _setContext(context); var entry = await _entryRepository.GetAsync(entryId); var remoteUrl = Flurl.Url.Combine(_appSettings.ApiUrl, audioUrl); Log($"Caching: {remoteUrl}"); var localFile = await _audioRetriever.RetrieveAudio( authToken, entry.Id, remoteUrl, "mp3"); Log($"Submitting waveform job for {localFile}"); var waveFormJobId = BackgroundJob.Enqueue <GenerateWaveformsJob>(job => job.ExecuteForEntry(entry.Id, localFile, null)); Log($"Submitting tag entry job for {localFile}"); var tagEntryJob = BackgroundJob.ContinueJobWith <TagEntryJob>( waveFormJobId, r => r.ExecuteForEntry(entry.Id, localFile, true, null)); Log($"Submitting upload job for {localFile}"); var tagEntryJobId = BackgroundJob.ContinueJobWith <UploadAudioJob>(tagEntryJob, job => job.Execute(entry.Id, localFile, null)); return(true); }
static void Main(string[] args) { GlobalConfiguration.Configuration .SetDataCompatibilityLevel(CompatibilityLevel.Version_170) .UseSimpleAssemblyNameTypeSerializer() .UseRecommendedSerializerSettings() .UseSqlServerStorage(@"Server=.\SQLEXPRESS;Database=Hangfire.Sample; Integrated Security=True;"); //Fire-and-Forget BackgroundJob.Enqueue(() => Console.WriteLine("Fire-and-Forget ")); //Recurring RecurringJob.AddOrUpdate(() => Console.WriteLine("Recurring "), Cron.Daily); //Delayed Jobs var jobId = BackgroundJob.Schedule(() => Console.WriteLine("10 seconds Delayed"), TimeSpan.FromSeconds(10)); //Continuations BackgroundJob.ContinueJobWith(jobId, () => Console.WriteLine("Continuations")); using (var server = new BackgroundJobServer()) { Console.ReadLine(); } }
public IActionResult BuyEVoucher(BuyEVoucherRequest _request) { string APIName = "BuyEVoucher"; log.LogInformation($"{APIName}\r\njson={StringHelper.SerializeObject(_request)}"); try { var response = repo.Estore.BuyEVoucher(_request); if (response.StatusCode == 200) { //First generate promocode when order success var generatePromoJobId = BackgroundJob.Enqueue(() => repo.Estore.ScheduleGeneratePromoCode(new GeneratePromoCodeRequest { PurchaseOrder_No = response.OrderNo })); //after promocode was generated add all to purchase history BackgroundJob.ContinueJobWith(generatePromoJobId, () => repo.Estore.ScheduleUpdatePaymentHistory()); log.LogInformation($"{APIName}\r\n Buy Success "); return(Ok(response)); } else { log.LogError($"{APIName}\r\nStautsCode:{response.StatusCode}\r\nErrorType:{response.ErrorType}" + $"\r\nErrorMsg:{response.ErrorMessage}"); return(StatusCode(response.StatusCode, response.GetError())); } } catch (Exception e) { log.LogError($"{APIName}\r\n{e}"); return(StatusCode(500, new Error("internal-error", e.Message))); } }
// 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.UseHttpsRedirection(); app.UseMvc(); var hangFireAuth = new DashboardOptions() { Authorization = new[] { new HangFireAuthorization(app.ApplicationServices.GetService <IAuthorizationService>(), app.ApplicationServices.GetService <IHttpContextAccessor>()), } }; app.UseHangfireServer(); RecurringJob.AddOrUpdate <IGenerateDailySalesReport>(s => s.ForAllCustomers(), Cron.Daily); var jobId = BackgroundJob.Enqueue(() => Console.WriteLine("a Fire-and-forget job!")); BackgroundJob.ContinueJobWith(jobId, () => Console.WriteLine("a Continuation!")); app.UseHangfireDashboard("/hangfire", hangFireAuth); }
public ResponseModel <AddContinueJobResponseModel> AddContinueJob([FromBody] List <HttpJobItem> httpJobItems) { ResponseModel <AddContinueJobResponseModel> responseModel = new ResponseModel <AddContinueJobResponseModel>(); responseModel.ResultData = new AddContinueJobResponseModel(); var reslut = string.Empty; var jobid = string.Empty; try { httpJobItems.ForEach(k => { if (!string.IsNullOrEmpty(jobid)) { jobid = BackgroundJob.ContinueJobWith(jobid, () => RunContinueJob(k)); } else { jobid = BackgroundJob.Enqueue(() => HttpJob.Excute(k, k.JobName, k.QueueName, k.IsRetry, null)); } }); reslut = "true"; responseModel.ResultData.Result = true; } catch (Exception ex) { responseModel.ResultCode = ResponseStatusCode.Error; responseModel.ResultDesc = ex.Message; } return(responseModel); }
public void BuildAndSend(string customer, int customerId) { var jobId = BackgroundJob.Enqueue(() => Console.WriteLine($"#{ customerId } - {customer} müşteri için {_name} jobı başladı.")); var job2Id = BackgroundJob.ContinueJobWith(jobId, () => PreparingReport(customer, customerId)); var job3Id = BackgroundJob.ContinueJobWith(job2Id, () => CreatingFile(customer, customerId)); var job4Id = BackgroundJob.ContinueJobWith(job3Id, () => SendNotification(customer, customerId)); }
public IActionResult Notification() { var jobId = BackgroundJob.Schedule(() => Console.WriteLine("Check, is status updated"), TimeSpan.FromSeconds(50)); BackgroundJob.ContinueJobWith(jobId, () => Console.WriteLine("Status Updated")); return(Ok($"Notifaction updated")); }
public async Task <string> AddContinuationsJobAsync(string parentJobId, string jobName, string callAddress, string paramJson, string group, string remarks) { var job = new Job { CallAddress = callAddress, CreatedBy = string.Empty, Name = jobName, Group = group, ParamJson = paramJson, JobType = JobType.ContinuationsJob.ToString(), ParentJobId = parentJobId, Remarks = remarks }; await _cronJobDbContext.AddAsync(job); try { job.HangfireJobId = BackgroundJob.ContinueJobWith <IJobWorker>( parentJobId, _ => _.DoWorkAsync(job.Id, callAddress, paramJson)); await _cronJobDbContext.SaveChangesAsync(); } catch (Exception ex) { BackgroundJob.Delete(job.HangfireJobId); throw ex; } return(job.Id); }
public JsonResult AddContinueJob([FromBody] List <Hangfire.HttpJob.Server.HttpJobItem> httpJobItems) { var reslut = string.Empty; var jobid = string.Empty; try { httpJobItems.ForEach(k => { if (!string.IsNullOrEmpty(jobid)) { jobid = BackgroundJob.ContinueJobWith(jobid, () => RunContinueJob(k)); } else { jobid = BackgroundJob.Enqueue(() => Hangfire.HttpJob.Server.HttpJob.Excute(k, k.JobName, k.QueueName, k.IsRetry, null)); } }); reslut = "true"; } catch (Exception ec) { return(Json(new Message() { Code = false, ErrorMessage = ec.ToString() })); } return(Json(new Message() { Code = true, ErrorMessage = "" })); }
private void CreateLinkedJobs(JobInfo jobInfo) { var jobId = BackgroundJob.Schedule(() => JobRunner.ExecuteJob(jobInfo), TimeSpan.FromSeconds(10)); BackgroundJob.ContinueJobWith(jobId, () => JobRunner.ExecuteJob(jobInfo)); }
public IActionResult Unsubscribe(string userName) { var jobId = BackgroundJob.Enqueue(() => UnsubscribeUser(userName)); BackgroundJob.ContinueJobWith(jobId, () => Console.WriteLine($"Sent Confirmation Mail to {userName}")); return(Ok($"Unsubscribed")); }
public async Task <bool> ProcessEntry(Guid entryId, PerformContext context) { var entry = await _entryRepository.GetAsync(entryId); try { var localFile = Path.Combine(Path.GetTempPath(), $"{entryId}.mp3"); var imageJobId = BackgroundJob.Enqueue <CacheRemoteImageJob>( r => r.CacheImage(entry.Id)); var extractJobId = BackgroundJob.Enqueue <IUrlProcessService>( r => r.DownloadAudio(entry.Id, localFile)); //TODO: Don't run this if IUrlProcessService fails var tagEntryJob = BackgroundJob.ContinueJobWith <TagEntryJob>( extractJobId, r => r.ExecuteForEntry(entry.Id, localFile, true, null)); var uploadJobId = BackgroundJob.ContinueJobWith <IAudioUploadProcessService>( tagEntryJob, r => r.UploadAudio(entry.Id, localFile)); //if we wait until everything is done, we can delete the local file var waveformJobId = BackgroundJob.ContinueJobWith <GenerateWaveformsJob>( extractJobId, r => r.ExecuteForEntry(entry.Id, localFile, null)); var cdnUrl = _options.GetSection("StorageSettings")["CdnUrl"]; var imageContainer = _options.GetSection("ImageFileStorageSettings")["ContainerName"]; context.WriteLine($"Submitting notify events"); BackgroundJob.ContinueJobWith <INotifyJobCompleteService>(uploadJobId, j => j.NotifyUser( entry.Podcast.AppUser.Id, "New Podcast Entry Available", $"{entry.Title} has finished processing", entry.Podcast.GetAuthenticatedUrl(_appSettings.SiteUrl), entry.Podcast.GetThumbnailUrl(cdnUrl, imageContainer), NotificationOptions.UploadCompleted )); BackgroundJob.ContinueJobWith <INotifyJobCompleteService>(uploadJobId, j => j.SendCustomNotifications( entry.Podcast.Id, entry.Podcast.AppUser.GetBestGuessName(), "PodNoms", $"{entry.Title} has finished processing", entry.Podcast.GetAuthenticatedUrl(_appSettings.SiteUrl) )); return(true); } catch (InvalidOperationException ex) { _logger.LogError($"Failed submitting job to processor\n{ex.Message}"); context.WriteLine($"Failed submitting job to processor\n{ex.Message}"); entry.ProcessingStatus = ProcessingStatus.Failed; await _unitOfWork.CompleteAsync(); return(false); } }
public string ContinueJobDemo() { //连续执行任务 var jobId = BackgroundJob.Schedule(() => Console.WriteLine($"Delay two minute:{DateTime.Now}"), TimeSpan.FromMinutes(2)); BackgroundJob.ContinueJobWith(jobId, () => Console.WriteLine("Continuation!")); return("OK"); }
/// <summary> /// api/HangfireJobCRUD/ContinueWithJob /// 添加依赖任务 /// </summary> /// <returns>任务ID</returns> public IActionResult ContinueWithJob() { string stepJobID1 = BackgroundJob.Enqueue(() => Console.WriteLine("Step1!")); string stepJobID2 = BackgroundJob.ContinueJobWith(stepJobID1, () => Console.WriteLine("Step2!"), JobContinuationOptions.OnlyOnSucceededState); string stepJobID3 = BackgroundJob.ContinueJobWith(stepJobID2, () => Console.WriteLine("Step3!"), JobContinuationOptions.OnAnyFinishedState); return(new JsonResult(new { stepJobID1, stepJobID2, stepJobID3 })); }
public IActionResult Comfirmar() { int timeInSeconds = 30; var parentJobId = BackgroundJob.Schedule(() => Console.WriteLine("Voce pediu para remover sua inscrição"), TimeSpan.FromSeconds(timeInSeconds)); BackgroundJob.ContinueJobWith(parentJobId, () => Console.WriteLine("Voce não esta mais inscrito")); return(Ok("Confirmado a criação do Job!")); }
public IActionResult ContinousJob_Demo() { var parentJobId = BackgroundJob.Schedule(() => hangfireJobServices.MakeUnsubcribeRequest("html body here"), delay: TimeSpan.FromSeconds(10)); var childJobId = BackgroundJob.ContinueJobWith(parentJobId, () => hangfireJobServices.MakeUnsubscribeAndDeleteRecord("Done")); return(Ok($"continued job implemented {childJobId}")); }
public void TestMultiTask() { Console.WriteLine(DateTime.Now); var jobId = BackgroundJob.Schedule(() => Test.PrintInfo("task1"), TimeSpan.FromSeconds(7)); BackgroundJob.ContinueJobWith(jobId, () => Test.PrintInfo("task2")); }
public IActionResult Confirm(int time) { var parentId = BackgroundJob.Schedule(() => Console.WriteLine("You asked to be unsubscribed"), TimeSpan.FromSeconds(time)); BackgroundJob.ContinueJobWith(parentId, () => Console.WriteLine("You were unsubscribed")); return(Ok("Confirmation job created")); }
public IActionResult continuationJob() { var interval = 15; var parentJobID = BackgroundJob.Schedule(() => sendEmail("are you sure to change password?"), TimeSpan.FromSeconds(interval)); BackgroundJob.ContinueJobWith(parentJobID, () => sendEmail("Success.")); //var jobID = BackgroundJob.Schedule(() => sendEmail("Welcome to our apps"), TimeSpan.FromSeconds(interval)); return(Ok("Generated report initated.")); }
public void Start() { BackgroundJob.Enqueue <UserManager <User> >(m => m.FindByIdAsync("1")); string jobId = BackgroundJob.Schedule <UserManager <User> >(m => m.FindByIdAsync("2"), TimeSpan.FromMinutes(2)); BackgroundJob.ContinueJobWith <TestHangfireJob>(jobId, m => m.GetUserCount()); RecurringJob.AddOrUpdate <TestHangfireJob>(m => m.GetUserCount(), Cron.Minutely, TimeZoneInfo.Local); RecurringJob.AddOrUpdate <TestHangfireJob>(m => m.LockUser2(), Cron.Minutely, TimeZoneInfo.Local); }
public IActionResult Confirm() { int timeInSeconds = 30; var parentJobId = BackgroundJob.Schedule(() => Console.WriteLine("You asked to be Unsubscribed!"), TimeSpan.FromSeconds(timeInSeconds)); BackgroundJob.ContinueJobWith(parentJobId, () => Console.WriteLine("You were Unsubscribed!")); return(Ok("Confirmation app created")); }
/// <summary> /// Execute the command only once but when its parent job has been finished. /// </summary> /// <param name="request">Request to be send.</param> /// <param name="parentJobId">Parent job id.</param> /// <param name="continuationOption">Continuation option.</param> /// <returns>Unique identifier of a created job.</returns> public string SendCommand(IRequest request, string parentJobId, JobContinuationOptions continuationOption) { CheckIfOperationIsSupported(); var mediatorSerializedObject = SerializeObject(request); return(BackgroundJob.ContinueJobWith(parentJobId, () => _messageExecutor.ExecuteCommand(mediatorSerializedObject), continuationOption)); }
public IActionResult Continuation(string userName) { var jobId = BackgroundJob.Enqueue(() => _hangfireJobs.ContinuationEmail(userName)); BackgroundJob.ContinueJobWith( jobId, () => Console.WriteLine($"Transaction is successfully completed for {userName}")); return(Ok($"Transaction is successfully completed")); }
public IActionResult Confirm() { //In this demo BackgroundJob.Schedule() is used, in real world here should be BackgroundJob.Enqueue() double timeToDelay = 30.0; var parentJobId = BackgroundJob.Schedule(() => SendMessage("You want to subscribe to our service."), TimeSpan.FromSeconds(timeToDelay)); BackgroundJob.ContinueJobWith(parentJobId, () => Console.WriteLine("You are successfully subscribed!")); return(Ok("Confirmation job is created!")); }
public IActionResult Confirmation() { // jobs Flow int timeInSecconds = 20; var parentJob = BackgroundJob.Schedule(() => Console.WriteLine("You are in process of unsubscribing from our service"), TimeSpan.FromSeconds(timeInSecconds)); BackgroundJob.ContinueJobWith(parentJob, () => Console.WriteLine("Your email was removed from our list")); return(Ok("Confirmation is processing")); }
public string GenerateContinuationJob <T>(string parentId, T item, CancellationToken cancellationToken) where T : BaseJobConfiguration { logger.LogDebug($"Start creating a delayed job named:{item.Name}"); var identifier = BackgroundJob.ContinueJobWith(parentId, () => Create <T>().Run(item, cancellationToken, performContext), JobContinuationOptions.OnlyOnSucceededState); logger.LogDebug($"Finish creating a delayed job named:{item.Name}"); return(identifier); }
public IActionResult Get() { var jobFireForget = BackgroundJob.Enqueue(() => Console.WriteLine($"Disparar agora: {DateTime.Now}")); var jobDelayed = BackgroundJob.Schedule(() => Console.WriteLine($"Com Delay: {DateTime.Now}"), TimeSpan.FromSeconds(10)); BackgroundJob.ContinueJobWith(jobDelayed, () => Console.WriteLine($"Continuação: {DateTime.Now}")); RecurringJob.AddOrUpdate(() => Console.WriteLine($"Job Recorrente: {DateTime.Now}"), Cron.Minutely); return(Ok("Jobs criados com sucesso")); }
public IActionResult Index() { var id = BackgroundJob.Enqueue(() => DoSomeTask()); // to start the second task after the completion of first one. The second task will be in que until the completion of first task BackgroundJob.ContinueJobWith(id, () => DoSomeOtherTask()); var jobId = BackgroundJob.Schedule(() => Console.WriteLine("Delayed!"), TimeSpan.FromDays(7)); return(View()); }