public JsonResult RunNotificationsAlgorithm(int Id, int Period, bool Enable, bool OnStopError, bool Invoke) { string msg = "Enabled"; if (Enable) { try { int UNHour, UNMinute; DateTimeServices.GetTimeUniversal(9, 0,User.Identity.GetTimeZone(), out UNHour, out UNMinute); RecurringJob.AddOrUpdate(Id.ToString(), () => EmploymentPapers.RunNotificationsAlgorithm(System.Configuration.ConfigurationManager.ConnectionStrings["HrContext"].ConnectionString,Language), Cron.Daily(UNHour,UNMinute)); } catch { if (OnStopError) RecurringJob.RemoveIfExists(Id.ToString()); } if (!Invoke) { RecurringJob.Trigger(Id.ToString()); EmploymentPapers _EmploymentPapers = new EmploymentPapers(HrUnitOfWork); _EmploymentPapers.UpdateTimeofTask(Id,Language); } } else msg = "Disabled"; return Json(msg, JsonRequestBehavior.AllowGet); }
public Task HandleMessage(Message message) { var jobName = message.Text.Split(' ', StringSplitOptions.RemoveEmptyEntries).ElementAtOrDefault(1); RecurringJob.Trigger(jobName); return(Task.CompletedTask); }
public static IApplicationBuilder SetupHangfire(this IApplicationBuilder app) { if (app == null) { throw new ArgumentNullException(nameof(app)); } RecurringJob.AddOrUpdate <Job>( "abc", d => d.Run(), "*/5 * * * *"); RecurringJob.Trigger("abc"); //if (configuration == null) throw new ArgumentNullException(nameof(configuration)); //if (configuration.JobSettings == null) throw new ArgumentNullException(nameof(configuration.JobSettings), "No JobSettings configuration file found."); //foreach (KeyValuePair<string, JobSettings> jobSettings in configuration.JobSettings.OrderByDescending(d => d.Key)) //{ // string jobIdentifier = jobSettings.Key; // RecurringJob.AddOrUpdate<ChannelJob>( // jobIdentifier, // d => d.Run(jobSettings.Value, configuration.ApplicationSettings), // jobSettings.Value.Cron); // if (jobSettings.Value.TriggerOnStart) // { // RecurringJob.Trigger(jobIdentifier); // } //} return(app); }
public static void RegisterJob( string jobId, Expression <Action> methodCall, Func <string> cronExpression, TimeZoneInfo timeZone = null, string queue = "default" ) { var sw = Stopwatch.StartNew(); Log.Debug("Registering Job with ID: {JobId}", jobId); RecurringJob.RemoveIfExists(jobId); RecurringJob.AddOrUpdate( jobId, methodCall, cronExpression, timeZone, queue ); RecurringJob.Trigger(jobId); Log.Debug( "Registering Job {JobId} finish in {Elapsed}", jobId, sw.Elapsed ); sw.Stop(); }
/// <summary> /// Trigger sharding job, trigger all RecurringJob we added /// </summary> /// <param name="name">job name</param> public static void Trigger(string name) { for (int i = 0; i < MaxSharding; i++) { RecurringJob.Trigger($"{name}_{i}"); } }
public static void CreateRecurringJob <T>(string jobName, Expression <Func <T, Task> > methodCall, string cronSchedule = null, string queue = "default") { // override if jobName is available in the settings file. string cronOverride = CronFromConfig(jobName); cronSchedule = (!string.IsNullOrEmpty(cronOverride)) ? cronOverride : cronSchedule ??= Cron.Daily(22, 30); var connection = JobStorage.Current.GetConnection(); Globals.DefaultConfiguration.GetSection(jobName); RecurringJob.AddOrUpdate <T>( recurringJobId: jobName, methodCall: methodCall, cronExpression: cronSchedule, timeZone: TimeZoneInfo.Local, queue: queue); RecurringJobDto newJob = connection.GetRecurringJobs(new string[] { jobName }).First(); if (newJob.LastExecution is null) { RecurringJob.Trigger(jobName); } }
// This method gets called by the runtime. Use this method to add services to the container. // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940 public new void ConfigureServices(IServiceCollection services) { services.AddTransient <Ultimate.ORM.IObjectMapper, Ultimate.ORM.ObjectMapper>(); services.AddSingleton <AutoMapper.IMapper>(new AutoMapper.Mapper(Mapping.CreateMapperConfiguration())); services.AddTransient <IWaveformTestPulseGeneratorProvider, WaveformTestPulseGeneratorProvider>(); services.AddTransient <IJobScheduler, JobScheduler>(); services.AddTransient <IJobProgressProvider, JobProgressProvider>(); services.AddTransient <FileCreator>(); services.AddTransient <IUltimateContainerProvider, UltimateContainerProvider>(); services.AddTransient <IOutputDirectoryProvider, WebOutputDirectoryProvider>(); services.AddSingleton <RecaptchaVerifier>(); services.AddHangfire(x => { x.UseSqlServerStorage(Configuration.GetConnectionString("DefaultConnection")); RecurringJob.AddOrUpdate(nameof(DeleteOldFiles), () => DeleteOldFiles(), "15 7 * * * *"); RecurringJob.Trigger(nameof(DeleteOldFiles)); }); services.AddHangfireServer(); services.AddLogging(c => { c.AddConsole(); c.AddAzureWebAppDiagnostics(); }); }
static void Main(string[] args) { GlobalConfiguration.Configuration.UseMemoryStorage(); var host = new WebHostBuilder() .UseKestrel() //.UseLoggerFactory(Logs.Factory) .UseContentRoot(Directory.GetCurrentDirectory()) //.UseIISIntegration() .UseStartup <Startup>() .Build(); //sample code of getting registered logger factory class //var loggerFactory = host.Services.GetService<ILoggerFactory>(); //loggerFactory.CreateLogger<Program>().LogInformation("test"); //var logger = host.Services.GetService<ILogger<Program>>(); //logger.LogInformation("Direct logging test"); //sample get another registered service //var jobActicator = host.Services.GetService<JobActivator>(); //Console.WriteLine(jobActicator.GetType()); RecurringJob.AddOrUpdate <CheckLinkJob>("check-link", j => j.Execute(), Cron.Minutely); RecurringJob.Trigger("check-link"); //RecurringJob.AddOrUpdate(() => Console.WriteLine("Simple!"), Cron.Minutely); host.Run(); }
private void StartRepo(object sender, System.Windows.RoutedEventArgs e) { if (isStarted) { RecurringJob.RemoveIfExists("backup-1"); repo?.Dispose(); StartButton.Content = "Старт"; isStarted = false; ListCommit.Items.Clear(); return; } if (!EnsureDirectoryIsExists()) { MessageBox.Show("Путь хрень"); return; } var path = GetDirectory(); EnsureGitIsInit(path); CreateRepoConnection(path); LoadBrunches(); LoadCommits(); //MessageBox.Show("AddTask"); RecurringJob.AddOrUpdate("backup-1", () => ScheduleMethod(), Cron.Minutely); RecurringJob.Trigger("backup-1"); StartButton.Content = "Стоп"; isStarted = true; }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IServiceProvider serviceProvider) { // Registers Hangfire GlobalConfiguration.Configuration.UseActivator( new AspNetCoreJobActivator(serviceProvider.GetRequiredService <IServiceScopeFactory>())); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseHttpsRedirection(); app.UseHangfireDashboard(); app.UseHangfireServer(); RecurringJob.AddOrUpdate("FetchPostsEveryDay", () => BackgroundWorker.FetchPostsEveryDay(null, JobCancellationToken.Null), Cron.Hourly); RecurringJob.Trigger("FetchPostsEveryDay"); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); }
public static void ExecuteJob <T>(Expression <Action <T> > methodToExecute) { var interfacePath = methodToExecute.Type .ToString() .Split('.') .LastOrDefault(); var methodPath = methodToExecute .ToString() .Split('.') .LastOrDefault(); var interfaceName = Regex.Replace(interfacePath, "[^a-zA-Z0-9]", string.Empty); var methodName = Regex.Replace(methodPath, "[^a-zA-Z0-9]", string.Empty); if (string.IsNullOrEmpty(interfaceName)) { throw new ArgumentNullException("Can't resolve interface name, please use an interface as T"); } if (string.IsNullOrEmpty(methodName)) { throw new ArgumentNullException("Can't resolve method name, please use a valid method from an interface"); } var jobId = $"{interfaceName}.{methodName}"; RecurringJob.Trigger(jobId); }
public ActionResult ExtendContract(int Id, int Period, bool Enable, bool OnStopError, bool Invoke) { string msg = "Enabled"; if (Enable) { try { int UNHour, UNMinute; DateTimeServices.GetTimeUniversal(9, 0, User.Identity.GetTimeZone(), out UNHour, out UNMinute); RecurringJob.AddOrUpdate(Id.ToString(), () => HangFireJobs.ExtendContract(Language), Cron.Daily(UNHour, UNMinute)); } catch { if (OnStopError) { RecurringJob.RemoveIfExists(Id.ToString()); } } if (!Invoke) { RecurringJob.Trigger(Id.ToString()); var model = _hrUnitOfWork.Repository <SchedualTask>().Where(a => a.EventId == Id).FirstOrDefault(); UpdateTimeofTask(model); } } else { msg = "Disabled"; } return(Json(msg, JsonRequestBehavior.AllowGet)); }
/// <summary> /// 执行任务 /// </summary> /// <param name="method"></param> /// <param name="config"></param> public void Excete <T>(Action method, WorkerConfig config) where T : IBackgroundWorkerDo { Config = config; string cron = config.Cron.IsNullOrEmpty() ? Cron.MinuteInterval(config.IntervalSecond / 60) : config.Cron; RecurringJob.AddOrUpdate <T>(config.WorkerId, (t) => t.DoWork(), cron, TimeZoneInfo.Local); RecurringJob.Trigger(config.WorkerId); }
public virtual void TriggerRecurringBackgroundJob(string jobId) { if (jobId == null) { throw new ArgumentNullException(nameof(jobId)); } RecurringJob.Trigger(jobId); }
private async void TimerRefreshFromWebApi_Elapsed(object sender, ElapsedEventArgs e) { try { logger.Trace(string.Format("WebApi refresh at {0}", DateTime.Now.ToString("o"))); List <string> activeJobs = new List <string>(); var result = await webapi.LoadBackupConfigurations(); if (result != null) { foreach (var item in result) { try { string jobId = $"{item.Id}";// _{Convert.ToBase64String(item.RowVersion)}"; if (item.IsActive.Value) { //RecurringJob. var recJob = JobStorage.Current.GetMonitoringApi().JobDetails(jobId); //RecurringJob.AddOrUpdate(jobId, () => LanCopyFileJob(item), item.Crontab); if (recJob == null) { RecurringJob.AddOrUpdate(jobId, () => DoCopyJob(item), item.Crontab); } activeJobs.Add(jobId); RecurringJob.Trigger(jobId); } else { //stopping inactive var recJob = JobStorage.Current.GetMonitoringApi().JobDetails(jobId); if (recJob != null) { RecurringJob.RemoveIfExists(jobId); } } } catch (Exception ex) { logger.Error($"Reccuring jobs refresh failed: {ex}"); //report error to webAPI webapi.LogActivity(item.Id, $"Reccuring jobs refresh failed -({item.Id})- see Err", ex.Message, "ERR"); } } } //TODO - purge ofphan jobs //JobStorage.Current.GetMonitoringApi().PurgeOrfanJobsExceptList(activeJobs); } catch (Exception ex) { logger.Error($"ERR WebApi refresh: {ex}"); //report error to webAPI webapi.LogActivity(string.Empty, "Reccuring jobs refresh final failed - see Err", ex.Message, "ERR"); } }
/// <summary> /// 触发任务 /// </summary> /// <param name="id"></param> public void Trigger(string id) { if (string.IsNullOrWhiteSpace(id)) { _logger.LogInformation("Can't trigger null job."); return; } _logger.LogInformation($"Trigger job: {id}."); RecurringJob.Trigger(id); }
private static void AddRecurringJobs(HangfireSettings hangfireSettings) { RecurringJob.RemoveIfExists(nameof(FillFilterCacheBackgroundJob)); RecurringJob.AddOrUpdate <FillFilterCacheBackgroundJob>( nameof(FillFilterCacheBackgroundJob), job => job.Execute(), hangfireSettings.Interval); RecurringJob.Trigger(nameof(FillFilterCacheBackgroundJob)); }
private static void StartSyncWordFilter() { const string jobId = "sync-word-filter"; Log.Debug("Starting cron Sync Word Filter to Local Storage"); RecurringJob.RemoveIfExists(jobId); RecurringJob.AddOrUpdate(jobId, () => Sync.SyncWordToLocalAsync(), Cron.Minutely); RecurringJob.Trigger(jobId); }
private void TriggerRecurringJobIfNeverExecuted(string jobName) { var connection = this.jobStorage.GetConnection(); var newJob = connection.GetRecurringJobs(new string[] { jobName }).First(); if (newJob.LastExecution is null) { RecurringJob.Trigger(jobName); } }
static void Main(string[] args) { //use the class OutputSettings //var outputFolder = configuration["output:folder"]; ////"reports"; //var outputFile = configuration["output:file"]; //"report.txt"; */ //override //dotnet run /output:folder=blah //dotnet run /output:folder=foo /output:file=bar.txt //configuration.GetSection("output:folder"]; // // var outputPath = $"{currentDirectory}/{outputFolder}/{outputFile}"; //var outputFolder = outputSettings.Folder; //var outputFile = outputSettings.File; //var outputPath = outputSettings.GetReportFilePath();//Path.Combine(currentDirectory,outputFolder,outputFile); //var directory = Path.GetDirectoryName(outputPath); // factory.AddDebug(); //var logger = Logs.Factory.CreateLogger("main"); //var config = new Config(args); //Logs.Init(config.ConfigurationRoot); GlobalConfiguration.Configuration.UseMemoryStorage(); // RecurringJob.AddOrUpdate(() => Console.WriteLine("\n\nRecurring Job\n\n"), Cron.Minutely); var host = new WebHostBuilder() .UseKestrel() .UseContentRoot(Directory.GetCurrentDirectory()) .UseStartup <Startup>() .Build(); //var log = host.Services.GetService<ILogger<Program>>(); //log.LogInformation("test"); //RecurringJob.AddOrUpdate<CheckLinkJob>("check-link", j => j.Execute(config.Site, config.Output), Cron.Minutely); // RecurringJob.AddOrUpdate<CheckLinkJob>("check-link", j => j.Execute(config.Site, config.Output), Cron.Minutely); RecurringJob.AddOrUpdate <CheckLinkJob>("check-link", j => j.Execute(), Cron.Minutely); RecurringJob.Trigger("check-link"); //RecurringJob.AddOrUpdate(() => Console.Write("simple"), Cron.Minutely); //using (var server = new BackgroundJobServer())//in start up hangfire server //{ // Console.WriteLine("Hangfire server started."); //Console.ReadKey();//add a web endpoint host.Run(); //} }
private static void StartLogCleanupScheduler() { var jobId = "logfile-cleanup"; var path = Path.Combine("Storage", "Logs"); Log.Debug($"Starting cron Log Cleaner with id {jobId}"); RecurringJob.RemoveIfExists(jobId); RecurringJob.AddOrUpdate(jobId, () => path.ClearLogs("Zizi", true), Cron.Hourly); RecurringJob.Trigger(jobId); }
public virtual Task TriggerRecurringBackgroundJobAsync(string jobId) { if (jobId == null) { throw new ArgumentNullException(nameof(jobId)); } RecurringJob.Trigger(jobId); return(Task.CompletedTask); }
private static void ScheduleVideoUpdate(Video video) { var jobId = $"Update {video.VideoId}"; var hash = Math.Abs(video.VideoId.GetHashCode()); RecurringJob.AddOrUpdate(jobId, () => UpdateVideo(video.VideoId), Cron.Weekly((DayOfWeek)(hash % 7), hash % 24, hash % 60)); if (string.IsNullOrEmpty(video.Title)) { RecurringJob.Trigger(jobId); } }
public IHttpActionResult Polling([FromUri] string terminalToken, [FromBody] PollingDataDTO pollingData) { Logger.Info($"Polling: requested for {pollingData.ExternalAccountId} from a terminal {terminalToken} and addition to jobId {pollingData.AdditionToJobId}"); pollingData.JobId = terminalToken + "|" + pollingData.ExternalAccountId + pollingData.AdditionToJobId; RecurringJob.AddOrUpdate(pollingData.JobId, () => SchedullerHelper.ExecuteSchedulledJob(pollingData, terminalToken), "*/" + pollingData.PollingIntervalInMinutes + " * * * *"); if (pollingData.TriggerImmediately) { RecurringJob.Trigger(pollingData.JobId); } return(Ok()); }
public IActionResult RunTrigger(int id) { try { RecurringJob.Trigger(id.ToString()); return(Ok()); } catch (Exception ex) { return(NotFound(ex.Message)); } }
public void CreateJobs() { _backgroundJobManager.Enqueue(new WriteToConsoleGreenJobArgs { Value = "test 1 (green)" }, BackgroundJobPriority.Low, System.TimeSpan.FromSeconds(30)); _backgroundJobManager.Enqueue(new WriteToConsoleGreenJobArgs { Value = "test 2 (green)" }, BackgroundJobPriority.High, System.TimeSpan.FromSeconds(32)); _backgroundJobManager.Enqueue(new WriteToConsoleYellowJobArgs { Value = "test 1 (yellow)" }, BackgroundJobPriority.Low, System.TimeSpan.FromSeconds(40)); _backgroundJobManager.Enqueue(new WriteToConsoleYellowJobArgs { Value = "test 2 (yellow)" }, BackgroundJobPriority.High, System.TimeSpan.FromSeconds(52)); //支持基于队列的任务处理:任务执行不是同步的,而是放到一个持久化队列中,以便马上把请求控制权返回给调用者。 var jobId = BackgroundJob.Enqueue(() => Console.WriteLine("队列任务")); BackgroundJob.Enqueue <HangfireJobExecutionAdapter <WriteToConsoleGreenJobArgs> > ( adapter => adapter.Execute(new WriteToConsoleGreenJobArgs { Value = "队列任务 2" }) ); //延迟任务执行:不是马上调用方法,而是设定一个未来时间点再来执行。 BackgroundJob.Schedule(() => Console.WriteLine("延时任务"), TimeSpan.FromSeconds(10)); BackgroundJob.Schedule <HangfireJobExecutionAdapter <WriteToConsoleYellowJobArgs> > ( adapter => adapter.Execute(new WriteToConsoleYellowJobArgs { Value = "延时任务 2" }), TimeSpan.FromSeconds(10)); //循环任务执行:一行代码添加重复执行的任务,其内置了常见的时间循环模式,也可基于CRON表达式来设定复杂的模式。 RecurringJob.AddOrUpdate("周期任务的名字", () => Console.WriteLine("每分钟执行任务"), Cron.Minutely); //注意最小单位是分钟 RecurringJob.AddOrUpdate <HangfireJobExecutionAdapter <WriteToConsoleYellowJobArgs> > ( adapter => adapter.Execute(new WriteToConsoleYellowJobArgs { Value = "每分钟执行任务 2" }), Cron.Minutely); //延续性任务执行:类似于.NET中的Task,可以在第一个任务执行完之后紧接着再次执行另外的任务 BackgroundJob.ContinueJobWith(jobId, () => Console.WriteLine("连续任务")); BackgroundJob.ContinueJobWith <HangfireJobExecutionAdapter <WriteToConsoleGreenJobArgs> > (jobId, adapter => adapter.Execute(new WriteToConsoleGreenJobArgs { Value = "连续任务 2" })); //删除指定的周期性任务 RecurringJob.RemoveIfExists("周期任务的名字"); //立即执行周期性任务: RecurringJob.Trigger("周期任务的名字"); }
public JsonResult Trigger(string jobName) { try { RecurringJob.Trigger(jobName); return(new JsonResult(new { Flag = true, Message = $"Job:{jobName}已触发执行" })); } catch (Exception ex) { return(new JsonResult(new { Flag = false, Message = ex.Message })); } }
public void TriggerJob(string id) { try { RecurringJob.Trigger(id); CustomJobModel job = GetJob(id); LogHistory(Guid.NewGuid(), id, job.ScriptType, DateTime.Now, "Trigger"); } catch (Exception ex) { throw new Exception($"Failed to trigger job: {id}. Error: {ex.Message}"); } }
public HttpResponseMessage TriggerReport(string id) { try { RecurringJob.Trigger(id); return(Request.CreateResponse(HttpStatusCode.OK, new SuccessResponse())); } catch (Exception ex) { return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex)); } }