Exemple #1
0
        static void Main(string[] args)
        {
            var port = GetAvailablePort(12345, 54321, IPAddress.Loopback);
            var url  = string.Format("http://localhost:{0}", port);

            using (WebApp.Start <Startup>(url))
            {
                Console.WriteLine("OWIN Server started at {0}", url);

                BackgroundJobServerOptions ops = new BackgroundJobServerOptions
                {
                    ServerName = url
                };
                using (var server = new BackgroundJobServer(ops))
                {
                    EventAggregator.JobStatusChanged += EventAggregator_JobStatusChanged;
                    EventAggregator.JobCompleted     += EventAggregator_JobCompleted;
                    EventAggregator.JobCountFound    += EventAggregator_JobCountFound;

                    Console.WriteLine("Hangfire Server started, dashboard at {0}/hangfire. Press ENTER to exit.", url);
                    Console.ReadLine();
                    server.SendStop();
                }
            }
        }
 public Task StopAsync(CancellationToken cancellationToken)
 {
     _server.SendStop();
     _server.Dispose();
     _logger.LogInformation("Hangfire Stopped");
     return(Task.CompletedTask);
 }
Exemple #3
0
        public Task StopAsync(CancellationToken cancellationToken)
        {
            Console.WriteLine("AcornBox.Worker - StopAsync - Entered");

            _backgroundJobServer?.SendStop();
            return(Task.CompletedTask);
        }
        public void Stop()
        {
            Console.WriteLine("I stopped");

            _backgroundJobServer.SendStop();
            _backgroundJobServer.Dispose();
        }
Exemple #5
0
 public override void OnApplicationShutdown(ApplicationShutdownContext context)
 {
     if (_backgroundJobServer != null)
     {
         _backgroundJobServer.SendStop();
         _backgroundJobServer.Dispose();
     }
 }
        public Task PreStop(IBus bus)
        {
            _server?.SendStop();

            LogContext.Debug?.Log("Hangfire Scheduler Paused: {InputAddress}", _schedulerEndpointAddress);

            return(TaskUtil.Completed);
        }
Exemple #7
0
 public void Stop(bool immediate)
 {
     lock (_lockObject)
     {
         if (_backgroundJobServer != null)
         {
             _backgroundJobServer.SendStop();
             _backgroundJobServer.Dispose();
         }
         HostingEnvironment.UnregisterObject(this);
     }
 }
 public void Stop(StopMessage msg)
 {
     //cleanup disposable resources
     if (timerRefreshFromWebApi != null)
     {
         timerRefreshFromWebApi.Stop();
         timerRefreshFromWebApi.Dispose();
     }
     if (hangfireServer != null)
     {
         hangfireServer.SendStop();
         hangfireServer.Dispose();
     }
     logger.Trace("LanCopyController Stopped");
 }
        private static Task Consumer(
            ILoggerFactory loggerFactory, JobStorage storage, CancellationToken token)
        {
            var server = new BackgroundJobServer(
                new BackgroundJobServerOptions {
                WorkerCount = 16
            },
                storage);

            return(Task.Run(
                       () => {
                token.WaitHandle.WaitOne();
                server.SendStop();
                server.WaitForShutdown(TimeSpan.FromSeconds(30));
            }, token));
        }
Exemple #10
0
        public static (BackgroundJobServer server, IRecurringJobManager recurringJobManager, IBackgroundJobClient backgroundJobClient) StartHangfireServer(
            BackgroundJobServerOptions options,
            string connectionString,
            IApplicationLifetime applicationLifetime,
            IJobFilterProvider jobFilters,
            JobActivator jobActivator,
            IBackgroundJobFactory backgroundJobFactory,
            IBackgroundJobPerformer backgroundJobPerformer,
            IBackgroundJobStateChanger backgroundJobStateChanger,
            IBackgroundProcess[] additionalProcesses
            )
        {
            JobStorage storage;

            if (string.IsNullOrWhiteSpace(connectionString))
            {
                storage = new MemoryStorage();
            }
            else if (ConnectionStringHelper.IsSQLite(connectionString))
            {
                storage = new SQLiteStorage(connectionString);
            }
            else
            {
                storage = new SqlServerStorage(connectionString);
            }

            var server = new BackgroundJobServer(options, storage, additionalProcesses,
                                                 options.FilterProvider ?? jobFilters,
                                                 options.Activator ?? jobActivator,
                                                 backgroundJobFactory,
                                                 backgroundJobPerformer,
                                                 backgroundJobStateChanger);

            applicationLifetime.ApplicationStopping.Register(() => server.SendStop());
            applicationLifetime.ApplicationStopped.Register(() => server.Dispose());

            var recurringJobManager = new RecurringJobManager(storage, backgroundJobFactory);

            var backgroundJobClient = new BackgroundJobClient(storage, backgroundJobFactory, backgroundJobStateChanger);

            return(server, recurringJobManager, backgroundJobClient);
        }
        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());
        }
Exemple #12
0
 public void Dispose()
 {
     jobServer.SendStop();
     jobServer.Dispose();
     scope.Dispose();
 }
 public void Stop()
 {
     Server.SendStop();
     Server.Dispose();
 }
Exemple #14
0
 public override void OnApplicationShutdown(ApplicationShutdownContext context)
 {
     //TODO: ABP may provide two methods for application shutdown: OnPreApplicationShutdown & OnApplicationShutdown
     _backgroundJobServer.SendStop();
     _backgroundJobServer.Dispose();
 }
Exemple #15
0
 public static void StopJobServer() => _backgroundJobServer?.SendStop();
        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;
        }