コード例 #1
0
ファイル: Startup.cs プロジェクト: mariusmuntean/DepthView
        private void InitHangfire(IAppBuilder app)
        {
            var hangfireConfig = IoC.Container.Resolve<IHangfireConfig>();
            GlobalConfiguration.Configuration.UseSqlServerStorage(
                hangfireConfig.SqlServerConnectionString,
                new SqlServerStorageOptions()
                {
                    PrepareSchemaIfNecessary = true,
                    QueuePollInterval = TimeSpan.FromSeconds(1)
                });
            GlobalJobFilters.Filters.Add(new AutomaticRetryAttribute { Attempts = 3 });

            app.UseHangfireDashboard("/hangfire", new DashboardOptions
            {
                AuthorizationFilters = new[] { new MyRestrictiveAuthorizationFilter() }
            });

            LogProvider.SetCurrentLogProvider(new ElmahLogProvider(LogLevel.Trace));

            var options = new BackgroundJobServerOptions
            {
                WorkerCount = Environment.ProcessorCount * 5
            };
            app.UseHangfireServer(options);

        }
コード例 #2
0
      public void ConfigureHangFire(IAppBuilder app)
      {
         var storageOptions = new SqlServerStorageOptions
         {
            InvisibilityTimeout = TimeSpan.FromHours(2),
            QueuePollInterval = TimeSpan.FromMinutes(15.0)
         };
         GlobalConfiguration.Configuration
            .UseSqlServerStorage("TrainingManagerDb", storageOptions);

         // case msmq installed
         /*GlobalConfiguration.Configuration
            .UseSqlServerStorage("TrainingManagerDb")
            .UseMsmqQueues(@".\hangfire-{0}");*/



         var dashboardOptions = new DashboardOptions
         {
            AuthorizationFilters = new[] { new AuthorizationFilter { Roles = AppConstants.UserRole.Administrator } }
         };
         app.UseHangfireDashboard("/hangfire", dashboardOptions);


         var jobServerOptions = new BackgroundJobServerOptions
         {
            WorkerCount = 1
         };
         app.UseHangfireServer(jobServerOptions);

         RecurringJob.AddOrUpdate(() => UpdateDaemon.ScheduledCatalogsUpdate(), Cron.Hourly);
      }
コード例 #3
0
ファイル: Startup.Job.cs プロジェクト: surifoll/git-test
       public void ConfigurationJob(IAppBuilder app)
       {

    

           var options = new BackgroundJobServerOptions
           {
               ServerName = String.Format(
                   "{0}.{1}",
                   CommonHelper.GetApplicationName, Environment.MachineName )

				        
           };
          var jobStorage = new SqlServerStorage(CommonHelper.GetJobConnectionString);
         
        //   var server = new BackgroundJobServer(options, jobStorage);

           app.UseHangfire(config =>
           {
               config.UseSqlServerStorage(CommonHelper.GetJobConnectionString);



               //var server = new BackgroundJobServer(options);
               config.UseServer(options);

               if (CommonHelper.EnableRemoteHangfire)
               config.UseAuthorizationFilters(new HangFireRestrictiveAuthorizationFilter());


           });
          // BackgroundJob.Enqueue(() => Debug.WriteLine("Hello, world!"));
       }
コード例 #4
0
        public void Configuration(IAppBuilder app)
        {
            GlobalConfiguration.Configuration.UseMemoryStorage();
            GlobalConfiguration.Configuration.UseNinjectActivator(NinjectWebCommon.kernel);

            app.UseHangfireDashboard();
            app.UseHangfireServer();
            var options = new BackgroundJobServerOptions();
            LogProvider.SetCurrentLogProvider(new RollbarLogProvider());
            RecurringJob.AddOrUpdate<SuperJob>(sb => sb.DoIt(), Cron.Minutely());
        }
コード例 #5
0
ファイル: Service1.cs プロジェクト: Skynetfy/MyTestProgram
 protected override void OnStart(string[] args)
 {
     string state = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss") + "启动";
     WriteLog(state);
    
     var options = new BackgroundJobServerOptions
     {
         Queues = new[] { "accordatapush" }
     };
     _server = new BackgroundJobServer(options);
 }
コード例 #6
0
        public static void UseServer(
            this IBootstrapperConfiguration configuration,
            int workerCount)
        {
            var options = new BackgroundJobServerOptions
            {
                WorkerCount = workerCount
            };

            configuration.UseServer(() => new BackgroundJobServer(options));
        }
コード例 #7
0
        public static void UseServer(
            this IBootstrapperConfiguration configuration,
            params string[] queues)
        {
            var options = new BackgroundJobServerOptions
            {
                Queues = queues
            };

            configuration.UseServer(() => new BackgroundJobServer(options));
        }
コード例 #8
0
        public BackgroundJobServer(BackgroundJobServerOptions options, JobStorage storage)
        {
            if (options == null) throw new ArgumentNullException("options");
            if (storage == null) throw new ArgumentNullException("storage");

            _options = options;
            _storage = storage;

            _serverId = String.Format("{0}:{1}", _options.ServerName.ToLowerInvariant(), Process.GetCurrentProcess().Id);

            // ReSharper disable once DoNotCallOverridableMethodsInConstructor
            _bootstrapSupervisor = GetBootstrapSupervisor();
        }
コード例 #9
0
        public void CreateServer()
        {
            BusinessLogic.Core.Base.IQueue queueBLL =
                Core.UnityConfig.Container.Resolve<BusinessLogic.Core.Base.IQueue>();

            List<Entities.Queue> queues = new List<Entities.Queue>();
            queues.Add(new Entities.Queue() { MaxWokers = -1, Name = HF.States.EnqueuedState.DefaultQueue });
            queues.AddRange(queueBLL.Select());

            HF.BackgroundJobServerOptions options = new HF.BackgroundJobServerOptions()
            {
                Queues = queues.ConvertAll(new Converter<Entities.Queue, HF.Server.Queue>(QueueToHFQueue)).ToArray()
            };

            Instance.Server = new HF.BackgroundJobServer(options);
        }
コード例 #10
0
ファイル: Startup.cs プロジェクト: AGRocks/HangfireExtension
        public void Configuration(IAppBuilder app)
        {
            ConfigureAuth(app);

            var options = new BackgroundJobServerOptions
            {
                WorkerCount = 10
            };

            GlobalConfiguration.Configuration
                .UseSQLiteStorage(@"Data Source=d:\temp\hangfire\hangfire.sqlite;Version=3;")
                .UseMsmqQueues(@".\private$\hangfire-test", "msmq");

            app.UseHangfireDashboard("/dashboard");
            app.UseHangfireServer(options);
        }
コード例 #11
0
        /// <summary>
        /// Initializes a new instance of the <see cref="BackgroundJobServer"/> class
        /// with the specified options and the given storage.
        /// </summary>
        /// <param name="options">Server options</param>
        /// <param name="storage">The storage</param>
        public BackgroundJobServer(BackgroundJobServerOptions options, JobStorage storage)
        {
            if (options == null) throw new ArgumentNullException("options");
            if (storage == null) throw new ArgumentNullException("storage");

            _options = options;
            _storage = storage;

            _serverId = String.Format("{0}:{1}", _options.ServerName.ToLowerInvariant(), Process.GetCurrentProcess().Id);

            // ReSharper disable once DoNotCallOverridableMethodsInConstructor
            _bootstrapSupervisor = GetBootstrapSupervisor();

            Logger.Info("Starting Hangfire Server");
            Logger.InfoFormat("Using job storage: '{0}'.", _storage);
            
            _storage.WriteOptionsToLog(Logger);
            _options.WriteToLog(Logger);

            _bootstrapSupervisor.Start();
        }
コード例 #12
0
ファイル: Startup.cs プロジェクト: surifoll/git-test
        public void Configuration(IAppBuilder app)
        {

            app.UseHangfire(config =>
            {
                config.UseSqlServerStorage(CommonHelper.GetJobConnectionString);

                var options = new BackgroundJobServerOptions
                {
                    ServerName = String.Format(
                        "{0}.{1}.{2}",
                        Environment.MachineName,
                        Guid.NewGuid().ToString(),CommonHelper.GetApplicationName)
                };

              

                config.UseServer(options);

            });
         
        }
コード例 #13
0
ファイル: Class1.cs プロジェクト: karabinier/api.lacage.be
        static void Main(string[] args)
        {
            XmlConfigurator.Configure(); //only once

            _log.Debug("Application is starting");

            if (args.Length > 0)
            {

                _storage = new SqlServerStorage(@"Data Source=.;Initial Catalog=SpriteHangFire;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False");
                var options = new BackgroundJobServerOptions();
                var server = new BackgroundJobServer(options, _storage);
                server.Start();
                
                Console.WriteLine("Hangfire Server started. Press any key to exit...");

                var input = Console.ReadKey();
                HandleInput(input);
                //using ()
                //{
                //    server.Start();


            }
            else
            {
                _log.Info("application launched without arguments");
                throw new NullReferenceException("kkkkkkjkljfkldsjfkl");
                //FileInfo f = new FileInfo();
                File.Create(string.Format(@"C:\TFSDATA\KissTheFuture\Trunk\shopping.lacage.be\shoppingconsole.lacage.be\bin\Debug\{0}.txt", Guid.NewGuid()));
                Thread.Sleep(5000);
            }
            
                //c.Schedule(() => MyJob.DoSomething(), TimeSpan.FromMinutes(10));
             
                //Console.ReadKey();
            //}
        }
コード例 #14
0
        public BackgroundJobServer(
            [NotNull] BackgroundJobServerOptions options,
            [NotNull] JobStorage storage,
            [NotNull] IEnumerable<IBackgroundProcess> additionalProcesses)
        {
            if (storage == null) throw new ArgumentNullException(nameof(storage));
            if (options == null) throw new ArgumentNullException(nameof(options));
            if (additionalProcesses == null) throw new ArgumentNullException(nameof(additionalProcesses));

            _options = options;

            var processes = new List<IBackgroundProcess>();
            processes.AddRange(GetRequiredProcesses());
            processes.AddRange(additionalProcesses);

            var properties = new Dictionary<string, object>
            {
                { "Queues", options.Queues },
                { "WorkerCount", options.WorkerCount }
            };

            Logger.Info("Starting Hangfire Server");
            Logger.Info($"Using job storage: '{storage}'");

            storage.WriteOptionsToLog(Logger);

            Logger.Info("Using the following options for Hangfire Server:");
            Logger.Info($"    Worker count: {options.WorkerCount}");
            Logger.Info($"    Listening queues: {String.Join(", ", options.Queues.Select(x => "'" + x + "'"))}");
            Logger.Info($"    Shutdown timeout: {options.ShutdownTimeout}");
            Logger.Info($"    Schedule polling interval: {options.SchedulePollingInterval}");
            
            _processingServer = new BackgroundProcessingServer(
                storage, 
                processes, 
                properties, 
                GetProcessingServerOptions());
        }
コード例 #15
0
ファイル: BackgroundJobServer.cs プロジェクト: pm100/Hangfire
        public BackgroundJobServer(
            [NotNull] BackgroundJobServerOptions options,
            [NotNull] JobStorage storage,
            [NotNull] IEnumerable <IBackgroundProcess> additionalProcesses,
            [NotNull] IJobFilterProvider filterProvider,
            [NotNull] JobActivator activator,
            [CanBeNull] IBackgroundJobFactory factory,
            [CanBeNull] IBackgroundJobPerformer performer,
            [CanBeNull] IBackgroundJobStateChanger stateChanger)
        {
            if (storage == null)
            {
                throw new ArgumentNullException(nameof(storage));
            }
            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }
            if (additionalProcesses == null)
            {
                throw new ArgumentNullException(nameof(additionalProcesses));
            }
            if (filterProvider == null)
            {
                throw new ArgumentNullException(nameof(filterProvider));
            }
            if (activator == null)
            {
                throw new ArgumentNullException(nameof(activator));
            }

            _options = options;

            var processes = new List <IBackgroundProcess>();

            processes.AddRange(GetRequiredProcesses(filterProvider, activator, factory, performer, stateChanger));
            processes.AddRange(additionalProcesses);

            var properties = new Dictionary <string, object>
            {
                { "Queues", options.Queues },
                { "WorkerCount", options.WorkerCount }
            };

            Logger.Info("Starting Hangfire Server");
            Logger.Info($"Using job storage: '{storage}'");

            storage.WriteOptionsToLog(Logger);

            Logger.Info("Using the following options for Hangfire Server:");
            Logger.Info($"    Worker count: {options.WorkerCount}");
            Logger.Info($"    Listening queues: {String.Join(", ", options.Queues.Select(x => "'" + x + "'"))}");
            Logger.Info($"    Shutdown timeout: {options.ShutdownTimeout}");
            Logger.Info($"    Schedule polling interval: {options.SchedulePollingInterval}");

            _processingServer = new BackgroundProcessingServer(
                storage,
                processes,
                properties,
                GetProcessingServerOptions());
        }
コード例 #16
0
 /// <summary>
 /// Initializes a new instance of the <see cref="BackgroundJobServer"/> class
 /// with the given options and <see cref="JobStorage.Current"/> storage.
 /// </summary>
 /// <param name="options">Server options</param>
 public BackgroundJobServer(BackgroundJobServerOptions options)
     : this(options, JobStorage.Current)
 {
 }
コード例 #17
0
 /// <summary>
 /// Initializes a new instance of the <see cref="BackgroundJobServer"/> class
 /// with the given options and <see cref="JobStorage.Current"/> storage.
 /// </summary>
 /// <param name="options">Server options</param>
 public BackgroundJobServer(BackgroundJobServerOptions options)
     : this(options, JobStorage.Current)
 {
 }
コード例 #18
0
ファイル: Program.cs プロジェクト: jeeva-selvaganesh/Hangfire
        public static void Main()
        {
            LogManager.Adapter = new ConsoleOutLoggerFactoryAdapter(
                LogLevel.Info, false, false, true, "");

            var sqlServerStorage = new SqlServerStorage(
                @"Server=.\sqlexpress;Database=Hangfire.Sample;Trusted_Connection=True;");
            sqlServerStorage.UseMsmqQueues(@".\Private$\hangfire{0}", "default", "critical");

            JobStorage.Current =
                sqlServerStorage;
                //new RedisStorage("localhost:6379", 3);

            RecurringJob.AddOrUpdate(() => Console.WriteLine("Hello, world!"), Cron.Minutely);
            RecurringJob.AddOrUpdate("hourly", () => Console.WriteLine("Hello"), Cron.Hourly);

            var options = new BackgroundJobServerOptions
            {
                Queues = new[] { "critical", "default" }
            };

            using (var server = new BackgroundJobServer(options))
            {
                var count = 1;

                while (true)
                {
                    var command = Console.ReadLine();

                    if (command == null || command.Equals("stop", StringComparison.OrdinalIgnoreCase))
                    {
                        break;
                    }

                    if (command.Equals("start", StringComparison.OrdinalIgnoreCase))
                    {
                        server.Start();
                    }

                    if (command.StartsWith("add", StringComparison.OrdinalIgnoreCase))
                    {
                        try
                        {
                            var workCount = int.Parse(command.Substring(4));
                            for (var i = 0; i < workCount; i++)
                            {
                                var number = i;
                                BackgroundJob.Enqueue<Services>(x => x.Random(number));
                            }
                            Console.WriteLine("Jobs enqueued.");
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine(ex.Message);
                        }
                    }

                    if (command.StartsWith("static", StringComparison.OrdinalIgnoreCase))
                    {
                        try
                        {
                            var workCount = int.Parse(command.Substring(7));
                            for (var i = 0; i < workCount; i++)
                            {
                                BackgroundJob.Enqueue(() => Console.WriteLine("Hello, {0}!", "world"));
                            }
                            Console.WriteLine("Jobs enqueued.");
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine(ex.Message);
                        }
                    }

                    if (command.StartsWith("error", StringComparison.OrdinalIgnoreCase))
                    {
                        var workCount = int.Parse(command.Substring(6));
                        for (var i = 0; i < workCount; i++)
                        {
                            BackgroundJob.Enqueue<Services>(x => x.Error());
                        }
                    }

                    if (command.StartsWith("args", StringComparison.OrdinalIgnoreCase))
                    {
                        var workCount = int.Parse(command.Substring(5));
                        for (var i = 0; i < workCount; i++)
                        {
                            BackgroundJob.Enqueue<Services>(x => x.Args(Guid.NewGuid().ToString(), 14442, DateTime.UtcNow));
                        }
                    }

                    if (command.StartsWith("custom", StringComparison.OrdinalIgnoreCase))
                    {
                        var workCount = int.Parse(command.Substring(7));
                        for (var i = 0; i < workCount; i++)
                        {
                            BackgroundJob.Enqueue<Services>(x => x.Custom(
                                new Random().Next(),
                                new []{ "Hello", "world!" },
                                new Services.CustomObject { Id = 123 },
                                DayOfWeek.Friday
                                ));
                        }
                    }

                    if (command.StartsWith("fullargs", StringComparison.OrdinalIgnoreCase))
                    {
                        var workCount = int.Parse(command.Substring(9));
                        for (var i = 0; i < workCount; i++)
                        {
                            BackgroundJob.Enqueue<Services>(x => x.FullArgs(
                                false,
                                123,
                                'c',
                                DayOfWeek.Monday,
                                "hello",
                                new TimeSpan(12, 13, 14),
                                new DateTime(2012, 11, 10),
                                new Services.CustomObject { Id = 123 },
                                new[] { "1", "2", "3" },
                                new[] { 4, 5, 6 },
                                new long[0],
                                null,
                                new List<string> { "7", "8", "9" }));
                        }
                    }

                    if (command.StartsWith("in", StringComparison.OrdinalIgnoreCase))
                    {
                        var seconds = int.Parse(command.Substring(2));
                        var number = count++;
                        BackgroundJob.Schedule<Services>(x => x.Random(number), TimeSpan.FromSeconds(seconds));
                    }

                    if (command.StartsWith("cancelable", StringComparison.OrdinalIgnoreCase))
                    {
                        var iterations = int.Parse(command.Substring(11));
                        BackgroundJob.Enqueue<Services>(x => x.Cancelable(iterations, JobCancellationToken.Null));
                    }

                    if (command.StartsWith("delete", StringComparison.OrdinalIgnoreCase))
                    {
                        var workCount = int.Parse(command.Substring(7));
                        for (var i = 0; i < workCount; i++)
                        {
                            var jobId = BackgroundJob.Enqueue<Services>(x => x.EmptyDefault());
                            BackgroundJob.Delete(jobId);
                        }
                    }

                    if (command.StartsWith("fast", StringComparison.OrdinalIgnoreCase))
                    {
                        try
                        {
                            var workCount = int.Parse(command.Substring(5));
                            Parallel.For(0, workCount, i =>
                            {
                                if (i % 2 == 0)
                                {
                                    BackgroundJob.Enqueue<Services>(x => x.EmptyCritical());
                                }
                                else
                                {
                                    BackgroundJob.Enqueue<Services>(x => x.EmptyDefault());
                                }
                            });
                            Console.WriteLine("Jobs enqueued.");
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine(ex.Message);
                        }
                    }
                }
            }

            Console.WriteLine("Press Enter to exit...");
            Console.ReadLine();
        }
コード例 #19
0
 public static void UseServer(
     this IBootstrapperConfiguration configuration,
     BackgroundJobServerOptions options)
 {
     configuration.UseServer(() => new BackgroundJobServer(options));
 }
コード例 #20
0
        private static BackgroundJobServerOptions SetupQueue(string queuePath, string queueName)
        {
            CreateQueueIfNecessary(queuePath);

            var options = new BackgroundJobServerOptions
            {
                ServerName = queueName,
                Queues = new[] { queueName }
            };

            return options;
        }
コード例 #21
0
 /// <summary>
 /// Initializes a new instance of the <see cref="BackgroundJobServer"/> class
 /// with the specified options and the given storage.
 /// </summary>
 /// <param name="options">Server options</param>
 /// <param name="storage">The storage</param>
 public BackgroundJobServer([NotNull] BackgroundJobServerOptions options, [NotNull] JobStorage storage)
     : this(options, storage, Enumerable.Empty <IBackgroundProcess>())
 {
 }
コード例 #22
0
 /// <summary>
 /// Creates a new instance of the <see cref="BackgroundJobServer"/> class
 /// with the specified options and <see cref="JobStorage.Current"/> storage,
 /// and registers its disposal on application shutdown.
 /// </summary>
 /// <param name="builder">OWIN application builder.</param>
 /// <param name="options">Options for background job server.</param>
 ///
 /// <exception cref="ArgumentNullException"><paramref name="builder"/> is null.</exception>
 /// <exception cref="ArgumentNullException"><paramref name="options"/> is null.</exception>
 /// <exception cref="InvalidOperationException">
 /// OWIN environment does not contain the application shutdown cancellation token.
 /// </exception>
 ///
 /// <remarks>
 /// Please see <see cref="AppBuilderExtensions"/> for details and examples.
 /// </remarks>
 public static IAppBuilder UseHangfireServer(
     [NotNull] this IAppBuilder builder,
     [NotNull] BackgroundJobServerOptions options)
 {
     return(builder.UseHangfireServer(options, JobStorage.Current));
 }
コード例 #23
0
ファイル: Program.cs プロジェクト: djrineh/Hangfire
        public static void Main()
        {
            GlobalConfiguration.Configuration
                .UseColouredConsoleLogProvider()
                .UseSqlServerStorage(@"Server=.\sqlexpress;Database=Hangfire.Sample;Trusted_Connection=True;")
                .UseMsmqQueues(@".\Private$\hangfire{0}", "default", "critical");

            RecurringJob.AddOrUpdate(() => Console.WriteLine("Hello, world!"), Cron.Minutely);
            RecurringJob.AddOrUpdate("hourly", () => Console.WriteLine("Hello"), "25 15 * * *");

            RecurringJob.AddOrUpdate("Hawaiian", () => Console.WriteLine("Hawaiian"),  "15 08 * * *", TimeZoneInfo.FindSystemTimeZoneById("Hawaiian Standard Time"));
            RecurringJob.AddOrUpdate("UTC", () => Console.WriteLine("UTC"), "15 18 * * *");
            RecurringJob.AddOrUpdate("Russian", () => Console.WriteLine("Russian"), "15 21 * * *", TimeZoneInfo.Local);

            var options = new BackgroundJobServerOptions
            {
                Queues = new[] { "critical", "default" }
            };

            using (new BackgroundJobServer(options))
            {
                var count = 1;

                while (true)
                {
                    var command = Console.ReadLine();

                    if (command == null || command.Equals("stop", StringComparison.OrdinalIgnoreCase))
                    {
                        break;
                    }

                    if (command.StartsWith("add", StringComparison.OrdinalIgnoreCase))
                    {
                        try
                        {
                            var workCount = int.Parse(command.Substring(4));
                            for (var i = 0; i < workCount; i++)
                            {
                                var number = i;
                                BackgroundJob.Enqueue<Services>(x => x.Random(number));
                            }
                            Console.WriteLine("Jobs enqueued.");
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine(ex.Message);
                        }
                    }

                    if (command.StartsWith("static", StringComparison.OrdinalIgnoreCase))
                    {
                        try
                        {
                            var workCount = int.Parse(command.Substring(7));
                            for (var i = 0; i < workCount; i++)
                            {
                                BackgroundJob.Enqueue(() => Console.WriteLine("Hello, {0}!", "world"));
                            }
                            Console.WriteLine("Jobs enqueued.");
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine(ex.Message);
                        }
                    }

                    if (command.StartsWith("error", StringComparison.OrdinalIgnoreCase))
                    {
                        var workCount = int.Parse(command.Substring(6));
                        for (var i = 0; i < workCount; i++)
                        {
                            BackgroundJob.Enqueue<Services>(x => x.Error());
                        }
                    }

                    if (command.StartsWith("args", StringComparison.OrdinalIgnoreCase))
                    {
                        var workCount = int.Parse(command.Substring(5));
                        for (var i = 0; i < workCount; i++)
                        {
                            BackgroundJob.Enqueue<Services>(x => x.Args(Guid.NewGuid().ToString(), 14442, DateTime.UtcNow));
                        }
                    }

                    if (command.StartsWith("custom", StringComparison.OrdinalIgnoreCase))
                    {
                        var workCount = int.Parse(command.Substring(7));
                        for (var i = 0; i < workCount; i++)
                        {
                            BackgroundJob.Enqueue<Services>(x => x.Custom(
                                new Random().Next(),
                                new []{ "Hello", "world!" },
                                new Services.CustomObject { Id = 123 },
                                DayOfWeek.Friday
                                ));
                        }
                    }

                    if (command.StartsWith("fullargs", StringComparison.OrdinalIgnoreCase))
                    {
                        var workCount = int.Parse(command.Substring(9));
                        for (var i = 0; i < workCount; i++)
                        {
                            BackgroundJob.Enqueue<Services>(x => x.FullArgs(
                                false,
                                123,
                                'c',
                                DayOfWeek.Monday,
                                "hello",
                                new TimeSpan(12, 13, 14),
                                new DateTime(2012, 11, 10),
                                new Services.CustomObject { Id = 123 },
                                new[] { "1", "2", "3" },
                                new[] { 4, 5, 6 },
                                new long[0],
                                null,
                                new List<string> { "7", "8", "9" }));
                        }
                    }

                    if (command.StartsWith("in", StringComparison.OrdinalIgnoreCase))
                    {
                        var seconds = int.Parse(command.Substring(2));
                        var number = count++;
                        BackgroundJob.Schedule<Services>(x => x.Random(number), TimeSpan.FromSeconds(seconds));
                    }

                    if (command.StartsWith("cancelable", StringComparison.OrdinalIgnoreCase))
                    {
                        var iterations = int.Parse(command.Substring(11));
                        BackgroundJob.Enqueue<Services>(x => x.Cancelable(iterations, JobCancellationToken.Null));
                    }

                    if (command.StartsWith("delete", StringComparison.OrdinalIgnoreCase))
                    {
                        var workCount = int.Parse(command.Substring(7));
                        for (var i = 0; i < workCount; i++)
                        {
                            var jobId = BackgroundJob.Enqueue<Services>(x => x.EmptyDefault());
                            BackgroundJob.Delete(jobId);
                        }
                    }

                    if (command.StartsWith("fast", StringComparison.OrdinalIgnoreCase))
                    {
                        try
                        {
                            var workCount = int.Parse(command.Substring(5));
                            Parallel.For(0, workCount, i =>
                            {
                                if (i % 2 == 0)
                                {
                                    BackgroundJob.Enqueue<Services>(x => x.EmptyCritical());
                                }
                                else
                                {
                                    BackgroundJob.Enqueue<Services>(x => x.EmptyDefault());
                                }
                            });
                            Console.WriteLine("Jobs enqueued.");
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine(ex.Message);
                        }
                    }

                    if (command.StartsWith("generic", StringComparison.OrdinalIgnoreCase))
                    {
                        BackgroundJob.Enqueue<GenericServices<string>>(x => x.Method("hello", 1));
                    }

                    if (command.StartsWith("continuations", StringComparison.OrdinalIgnoreCase))
                    {
                        WriteString("Hello, Hangfire continuations!");
                    }
                }
            }

            Console.WriteLine("Press Enter to exit...");
            Console.ReadLine();
        }
コード例 #24
0
 public static void UseServer(
     this IBootstrapperConfiguration configuration,
     JobStorage storage,
     BackgroundJobServerOptions options)
 {
     configuration.UseServer(() => new BackgroundJobServer(options, storage));
 }