private async void JobProcessing() { var options = new BackgroundJobServerOptions { WorkerCount = 1, ServerName = "Pochinki-Bot", SchedulePollingInterval = TimeSpan.FromSeconds(10) }; using (var jobServer = new BackgroundJobServer(options)) { await jobServer.WaitForShutdownAsync(_tokenSource.Token); } }
public async Task ExecuteAsync() { var storage = new MySqlStorage(AppSettings.ConnectionStrings); //if (AppSettings.EnableDb == "MySql") //{ // var storage = new MySqlStorage(AppSettings.ConnectionStrings); // service.UseDataSynchronizationjob(storage); //} var _storage = storage as MySqlStorage; GlobalConfiguration.Configuration.UseStorage(storage as MySqlStorage); RecurringJob.AddOrUpdate(() => Console.WriteLine("Hangfire AddOrUpdate任务"), "1/5 * * * * *", TimeZoneInfo.Local, "queue1"); BackgroundJobServer jobServer = new BackgroundJobServer(new BackgroundJobServerOptions() { Queues = new string[] { "queue1", "queue2" }, ServerName = "ControlCenterServices", WorkerCount = 1 }, _storage); await jobServer.WaitForShutdownAsync(CancellationToken.None); }
public async Task Invoke(HttpContext httpContext) { var start = LocalTime.Now; Console.WriteLine("Invoking DistributedBackgroundTasksMiddleware at " + start); JobStorage.Current = new SqlServerStorage(Context.Current.GetService <IConnectionStringProvider>().GetConnectionString()); var cancellationResource = new CancellationTokenSource(); var token = cancellationResource.Token; using (var server = new BackgroundJobServer()) { await Task.Delay(TimeSpan.FromSeconds(Config.Get <int>("Automated.Tasks:Action.Delay", 5)), token); // Optional delay to catch some more background jobs server.SendStop(); await server.WaitForShutdownAsync(token); } httpContext.Response.ContentType = "text/plain"; httpContext.Response.Clear(); httpContext.Response.Write("Done"); Console.WriteLine("Invoked DistributedBackgroundTasksMiddleware after " + LocalTime.Now.Subtract(start).ToNaturalTime()); }
protected override async Task ExecuteAsync(CancellationToken stoppingToken) { if (string.IsNullOrEmpty(this.hangfireConfig.ConnectionString)) { throw new ArgumentNullException(nameof(this.hangfireConfig.ConnectionString)); } var childScope = ServiceScope = this.rootScope.BeginLifetimeScope("HangfireServiceScope"); var activator = new AutofacLifecycleJobActivator(childScope); var options = new BackgroundJobServerOptions() { Activator = activator, Queues = this.hangfireConfig.Queues ?? JobQueue.Queues }; await this.InitializeStorage(); this.startupHandler.PostConfigure(this.rootScope as IServiceProvider); using (var server = new BackgroundJobServer(options)) { await server.WaitForShutdownAsync(stoppingToken); } }
public async Task StartAsync(CancellationToken cancellationToken) { SetConfiguration(); ServiceCollections = new ServiceCollection(); ConfigureServices(ServiceCollections); ILogger <Program> logger = ServiceProvider.GetService <ILogger <Program> >(); logger.LogInformation("启动服务"); try { //var doPublishEventTestService = ServiceProvider.GetService<DoPublishEventTestService>(); //await doPublishEventTestService.OnStart(); //Console.WriteLine("123"); //使用Autofac必须再全局配置GlobalConfiguration.Configuration.UseRedisStorage后面启用, //且创建BackgroundJobServer必须放在UseAutofacActivator方法后面,不然无效。 // 部分问题:BackgroundJobServer以全局实例注入后,无法获取到 _redisStorage.UseAutofacActivator(ApplicationContainer); //ServiceCollections.AddSingleton(redisStorage); foreach (var backgroundJobServerOption in JobServerOptionsList) { //如要按队列来分配后台作业服务器,则可创建多个后台作业服务器实例 var backgroundJobServer = new BackgroundJobServer(backgroundJobServerOption, _redisStorage.Entry); _backgroundJobServerList.Add(backgroundJobServer); } //_backgroundJobServer ??= new BackgroundJobServer(JobServerOptions); // Autofac接管前可用 //ServiceCollections.AddSingleton(_backgroundJobServer); // Autofac接管后需要用Aufofac的注入 //AppContainerBuilder.RegisterInstance(_backgroundJobServer).SingleInstance(); //AppContainerBuilder.RegisterInstance<BackgroundJobServer>(_backgroundJobServer).SingleInstance(); //BackgroundJob.Enqueue<TestJob>(x => x.CallUrl("https://www.qq.com", "ConsoleServerJob")); //BackgroundJob.Enqueue<GetNewsJob>(x => x.GetNewsByUrl("https://www.qq.com", "获取腾讯新闻")); var backgroundJobServer2 = ServiceProvider.GetService <BackgroundJobServer>(); var backgroundJobClient = ServiceProvider.GetService <IBackgroundJobClient>(); //注意,执行job方法里 的PerformContext参数必须填null backgroundJobClient.Enqueue <GetNewsJob>(t => t.GetBaiduNews("获取百度新闻1111123", null)); } catch (Exception ex) { Console.WriteLine("启动出错"); logger.LogError("启动报错:" + ex); /* * if (_backgroundJobServer != null) * { * await _backgroundJobServer.WaitForShutdownAsync(cancellationToken); * _backgroundJobServer.SendStop(); * _backgroundJobServer.Dispose(); * } */ if (_backgroundJobServerList.Count > 1) { foreach (var backgroundJobServer in _backgroundJobServerList) { await backgroundJobServer.WaitForShutdownAsync(cancellationToken); backgroundJobServer.SendStop(); backgroundJobServer.Dispose(); } } Console.ReadKey(); } //return Task.CompletedTask; }