public async Task <string> AddOrUpdateRecurringJobAsync(string jobId, string jobName, string callAddress, string paramJson, string cron, string group, string remarks, string createdBy) { Job job = null; if (string.IsNullOrWhiteSpace(jobId)) { string newId = Guid.NewGuid().ToString(); job = new Job { Id = newId, CallAddress = callAddress, CreatedBy = createdBy, Name = jobName, JobType = JobType.RecurringJob.ToString(), Cron = cron, CronDescription = await _cronTranslator.TranslateCron2DescriptionAsync(cron), ParamJson = paramJson, Group = group, HangfireJobId = newId, Remarks = remarks, CreatedOn = DateTime.Now }; await _cronJobDbContext.Jobs.AddAsync(job); jobId = job.Id; } else { job = await _cronJobDbContext.Jobs.FindAsync(jobId); if (job == null) { throw new InvalidOperationException($"can't find job {jobId}"); } } try { RecurringJob.AddOrUpdate <IJobWorker>(jobId, x => x.DoWorkAsync(jobId, callAddress, paramJson), cron, TimeZoneInfo.Local); await _cronJobDbContext.SaveChangesAsync(); } catch (Exception ex) { RecurringJob.RemoveIfExists(job.Id); throw ex; } return(jobId); }
public async Task DoWorkAsync(string jobId, string callAddress, string paramJson) { paramJson = string.IsNullOrWhiteSpace(paramJson) ? string.Empty : paramJson; var job = await _cronJobDbContext.Jobs.FindAsync(jobId); if (job == null || !job.IsActive) { return; } var log = new JobLog { Id = Guid.NewGuid().ToString(), JobId = jobId, StartTime = DateTime.Now, IsSuccess = true }; using (var client = _httpClientFactory.CreateClient("http_client")) { try { var res = await client.PostAsync(callAddress, new StringContent(paramJson, Encoding.UTF8, "application/json")); log.IsSuccess = res.IsSuccessStatusCode; log.ResponseContent = await res.Content.ReadAsStringAsync(); log.EndTime = DateTime.Now; } catch (Exception e) { log.IsSuccess = false; log.ErrorMessage = e.Message; log.EndTime = DateTime.Now; } finally { job.LastExecuteTime = DateTime.Now; job.TriggeredTimes++; await _cronJobDbContext.JobLogs.AddAsync(log); await _cronJobDbContext.SaveChangesAsync(); } } }