public static void Main() { try { // you can use Raven Storage and specify the connection string name GlobalConfiguration.Configuration .UseColouredConsoleLogProvider() .UseRavenStorage("RavenDebug"); // you can use Raven Storage and specify the connection string and database name //GlobalConfiguration.Configuration // .UseColouredConsoleLogProvider() // .UseRavenStorage("http://localhost:9090", "HangfireConsole"); // you can use Raven Embedded Storage which runs in memory! //GlobalConfiguration.Configuration // .UseColouredConsoleLogProvider() // .UseEmbeddedRavenStorage(); //you have to create an instance of background job server at least once for background jobs to run var client = new BackgroundJobServer(); // Run once BackgroundJob.Enqueue(() => System.Console.WriteLine("Background Job: Hello, world!")); BackgroundJob.Enqueue(() => Test()); // Run every minute RecurringJob.AddOrUpdate(() => Test(), Cron.Minutely); System.Console.WriteLine("Press Enter to exit..."); System.Console.ReadLine(); } catch (Exception ex) { throw ex; } }
public static void RunHangfireServer( this IAppBuilder app, BackgroundJobServer server) { Servers.Add(server); server.Start(); var context = new OwinContext(app.Properties); var token = context.Get<CancellationToken>("host.OnAppDisposing"); if (token != CancellationToken.None) { token.Register(server.Dispose); } }
static void Main() { // log4net.Config.XmlConfigurator.Configure();00000000 logger = NLog.LogManager.GetCurrentClassLogger(); logger.Info("Worker Host process has been started"); unityContainer = UnityConfig.Register(); UnityConfig.ConfigureDefaults(unityContainer); var storage = new SqlServerStorage("HangfireStorageDbContext"); var options = new BackgroundJobServerOptions() { WorkerCount = 10 }; UnityJobActivator unityJobActivator = new UnityJobActivator(unityContainer); GlobalConfiguration.Configuration.UseActivator(unityJobActivator); JobActivator.Current = unityJobActivator; GlobalJobFilters.Filters.Add(new ChildContainerPerJobFilterAttribute(unityJobActivator)); var server = new BackgroundJobServer(options, storage); server.Start(); Thread.Sleep(300000); server.Stop(); }
public void HangfireService() { JobStorage.Current = new SqlServerStorage("connection_string"); _server = new BackgroundJobServer(); }
public void Start() { var options = new BackgroundJobServerOptions(); _server = new BackgroundJobServer(options); }
public override void Init() { base.Init(); JobActivator.Current = new WindsorJobActivator(Starter.Container.Kernel); _backgroundJobServer = new BackgroundJobServer(); }
public override void OnApplicationInitialization(ApplicationInitializationContext context) { var options = context.ServiceProvider.GetRequiredService <IOptions <AbpHangfireOptions> >().Value; _backgroundJobServer = options.BackgroundJobServerFactory.Invoke(context.ServiceProvider); }
public AbpHangfireBackgroundJobServer(BackgroundJobServer hangfireJobServer) { HangfireJobServer = hangfireJobServer; }
static int Main(string[] args) { Log.Logger = new LoggerConfiguration() .MinimumLevel.Verbose() .MinimumLevel.Override("Microsoft", LogEventLevel.Information) .Enrich.FromLogContext() .WriteTo.Debug() .WriteTo.LiterateConsole() .WriteTo.RollingFile("log-{Date}.txt", LogEventLevel.Debug) .CreateLogger(); try { Log.Information("Starting JobRunner host"); var enviromentName = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Production"; var builder = new Microsoft.Extensions.Configuration.ConfigurationBuilder() .AddJsonFile("appsettings.json") .AddJsonFile($"appsettings.{enviromentName}.json", true); var configuration = builder.Build(); var services = new ServiceCollection(); services.AddSingleton(p => configuration); services.AddLogging(b => b.AddSerilog()); services.AddOptions(); services.KickStart(config => config .IncludeAssemblyFor <TrainDTrainorContext>() .Data(ConfigurationServiceModule.ConfigurationKey, configuration) .Data("hostProcess", "runner") .UseAutoMapper() .UseStartupTask() ); var connectionString = configuration.GetConnectionString("TrainDTrainor"); var storageOptions = new SqlServerStorageOptions(); GlobalConfiguration.Configuration.UseSqlServerStorage(connectionString, storageOptions); var serverOptions = new BackgroundJobServerOptions(); using (var webJobHost = new WebJobHost()) using (var backgroundJobServer = new BackgroundJobServer(serverOptions)) { webJobHost.RunAndBlock(); } return(0); } catch (Exception ex) { Log.Fatal(ex, "Host terminated unexpectedly"); return(1); } finally { Log.CloseAndFlush(); } }
public bool Start(HostControl hostControl) { jobServer = new BackgroundJobServer(GetJobServerOptions()); RecurringJob.AddOrUpdate <IForwarder>(f => f.ReadAllTeamStatus(null), Cron.Minutely); return(true); }
public void Start() { _server = new BackgroundJobServer(); BackgroundTasks.Configure(); }
public HangfireJobServer(JobStorage storage) { _server = new BackgroundJobServer(storage); }
private SchedulerServer() { backgroundJobServer = new BackgroundJobServer(); }
public SchedulerWrapper() { JobStorage.Current = GlobalConfiguration.Configuration.UseMemoryStorage(); this.server = new BackgroundJobServer(); this.server.Start(); }
public void MultipleServerRunsRecurrentJobs() { // ARRANGE const int serverCount = 20; const int workerCount = 20; var options = new BackgroundJobServerOptions[serverCount]; var storage = ConnectionUtils.CreateStorage(new MongoStorageOptions { QueuePollInterval = TimeSpan.FromSeconds(1) }); var servers = new BackgroundJobServer[serverCount]; var jobManagers = new RecurringJobManager[serverCount]; for (int i = 0; i < serverCount; i++) { options[i] = new BackgroundJobServerOptions { Queues = new[] { $"queue_options_{i}" }, WorkerCount = workerCount }; servers[i] = new BackgroundJobServer(options[i], storage); jobManagers[i] = new RecurringJobManager(storage); } try { // ACT for (int i = 0; i < serverCount; i++) { var i1 = i; var jobManager = jobManagers[i1]; for (int j = 0; j < workerCount; j++) { var j1 = j; var queueIndex = j1 % options[i1].Queues.Length; var queueName = options[i1].Queues[queueIndex]; var job = Job.FromExpression(() => Console.WriteLine("Setting signal for queue {0}", queueName)); var jobId = $"job:[{i},{j}]"; jobManager.AddOrUpdate(jobId, job, Cron.Minutely(), new RecurringJobOptions { QueueName = queueName }); jobManager.Trigger(jobId); } } // let hangfire run for 1 sec Task.Delay(1000).Wait(); } finally { for (int i = 0; i < serverCount; i++) { servers[i].SendStop(); servers[i].Dispose(); } } }
public Task StartAsync(CancellationToken cancellationToken) { server = new BackgroundJobServer(options, storage, additionalProcesses); return(Task.CompletedTask); }
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; }
public void Start() { //RecurringJob.AddOrUpdate<IPublisherJob>("", x => x.Execute(), Cron.Minutely(), null); _server = new BackgroundJobServer(_options); }
public void Start() { _server = new BackgroundJobServer(); }
public virtual void Configuration(IAppBuilder appBuilder) { appBuilder.Use <OwinExceptionHandlerMiddleware>(Log.Logger); // Configure Web API for self-host. HttpConfiguration config = new HttpConfiguration(); config.Services.Replace(typeof(IExceptionHandler), new OwinExceptionHandlerMiddleware.PassthroughExceptionHandler()); config.MapHttpAttributeRoutes(); config.EnableSwagger(c => { c.SingleApiVersion("v1", "RPA web API"); c.DescribeAllEnumsAsStrings(); c.IncludeXmlComments("RpaSelfHostedApp.xml"); c.OperationFilter <SwaggerParameterOperationFilter>(); }) .EnableSwaggerUi(); appBuilder.UseWebApi(config); appBuilder.MapSignalR(); var container = appBuilder.RegisterDependencies(config); Hangfire.GlobalConfiguration.Configuration .UseLiteDbStorage() .UseLightInjectActivator(container) .UseSerilogLogProvider(); var physicalFileSystem = new PhysicalFileSystem(@".\Web"); //. = root, Web = your physical directory that contains all other static content, see prev step var options = new FileServerOptions { EnableDefaultFiles = true, FileSystem = physicalFileSystem, StaticFileOptions = { FileSystem = physicalFileSystem, ServeUnknownFileTypes = false }, DefaultFilesOptions = { DefaultFileNames = new[] { "index.html" } }, }; //put whatever default pages you like here appBuilder.UseFileServer(options); var properties = new AppProperties(appBuilder.Properties); CancellationToken token = properties.OnAppDisposing; var client = new BackgroundJobServer(new BackgroundJobServerOptions() { SchedulePollingInterval = TimeSpan.FromSeconds(1), ServerCheckInterval = TimeSpan.FromSeconds(1) }, JobStorage.Current); Action disposeObjects = () => { if (!_wasDisposed) { _wasDisposed = true; var fullNameOfDll = Assembly.GetExecutingAssembly().FullName; Log.Logger.Warning($"Close {this.GetType().FullName} application \n {fullNameOfDll}"); client.Dispose(); container.Dispose(); } }; if (token != CancellationToken.None) { client.WaitForShutdown(TimeSpan.FromSeconds(10)); token.Register(disposeObjects); } else { Log.Fatal("Error with application start"); } AppDomain.CurrentDomain.ProcessExit += (sender, args) => { disposeObjects(); }; }
public static void Launch( MessageBusConnectionConfiguration messageBusConnectionConfiguration, MessageBusLaunchConfiguration launchConfig, IHandlerFactory handlerFactory) { new { messageBusConnectionConfiguration }.AsArg().Must().NotBeNull(); new { launchConfig }.AsArg().Must().NotBeNull(); new { handlerFactory }.AsArg().Must().NotBeNull(); if (launchConfig.ChannelsToMonitor.Any(_ => _.GetType() != typeof(SimpleChannel))) { throw new NotSupportedException(Invariant($"Only {nameof(SimpleChannel)}'s are supported as the implementation of {nameof(IChannel)} for {nameof(launchConfig.ChannelsToMonitor)}.")); } var assembliesToRecord = new[] { typeof(HangfireHarnessManager).Assembly }.ToList(); if (handlerFactory is ReflectionHandlerFactory reflectionHandlerFactory) { assembliesToRecord.AddRange(reflectionHandlerFactory.FilePathToAssemblyMap.Values); } var processSiblingAssemblies = assembliesToRecord.Select(SafeFetchAssemblyDetails).ToList(); var dateTimeOfSampleInUtc = DateTime.UtcNow; var machineDetails = DomainFactory.CreateMachineDetails(); var processDetails = DomainFactory.CreateProcessDetails(); var diagnosticsTelemetry = new DiagnosticsTelemetry(dateTimeOfSampleInUtc, machineDetails, processDetails, processSiblingAssemblies); var serializerFactory = SerializerFactory.Instance; var compressorFactory = CompressorFactory.Instance; var logProvider = new HangfireLogProviderToNaosLogWritingAdapter(); LogProvider.SetCurrentLogProvider(logProvider); var activeMessageTracker = new InMemoryActiveMessageTracker(); var envelopeMachine = new EnvelopeMachine( PostOffice.MessageSerializerRepresentation, serializerFactory); var courier = new HangfireCourier(messageBusConnectionConfiguration.CourierPersistenceConnectionConfiguration, envelopeMachine); var parcelTrackingSystem = new ParcelTrackingSystem( courier, envelopeMachine, messageBusConnectionConfiguration.EventPersistenceConnectionConfiguration, messageBusConnectionConfiguration.ReadModelPersistenceConnectionConfiguration); var postOffice = new PostOffice(parcelTrackingSystem, HangfireCourier.DefaultChannelRouter, envelopeMachine); HandlerToolshed.InitializePostOffice(() => postOffice); HandlerToolshed.InitializeParcelTracking(() => parcelTrackingSystem); HandlerToolshed.InitializeSerializerFactory(() => serializerFactory); HandlerToolshed.InitializeCompressorFactory(() => compressorFactory); var shareManager = new ShareManager( serializerFactory); var handlerSharedStateMap = new ConcurrentDictionary <Type, object>(); var dispatcher = new MessageDispatcher( handlerFactory, handlerSharedStateMap, launchConfig.ChannelsToMonitor, diagnosticsTelemetry, parcelTrackingSystem, activeMessageTracker, postOffice, envelopeMachine, shareManager); // configure hangfire to use the DispatcherFactory for getting IDispatchMessages calls GlobalConfiguration.Configuration.UseActivator(new DispatcherFactoryJobActivator(dispatcher)); GlobalJobFilters.Filters.Add(new AutomaticRetryAttribute { Attempts = launchConfig.MessageDeliveryRetryCount }); var executorOptions = new BackgroundJobServerOptions { Queues = launchConfig.ChannelsToMonitor.OfType <SimpleChannel>().Select(_ => _.Name).ToArray(), SchedulePollingInterval = launchConfig.PollingInterval, WorkerCount = launchConfig.ConcurrentWorkerCount, }; GlobalConfiguration.Configuration.UseSqlServerStorage( messageBusConnectionConfiguration.CourierPersistenceConnectionConfiguration.ToSqlServerConnectionString(), new SqlServerStorageOptions()); var launchConfigTimeToLive = launchConfig.TimeToLive; if (launchConfigTimeToLive == default(TimeSpan)) { launchConfigTimeToLive = TimeSpan.MaxValue; } var timeout = DateTime.UtcNow.Add(launchConfigTimeToLive); // ReSharper disable once UnusedVariable - good reminder that the server object comes back and that's what is disposed in the end... using (var server = new BackgroundJobServer(executorOptions)) { Console.WriteLine(Invariant($"Hangfire Server started. Will terminate when there are no active jobs after: {timeout}.")); Log.Write(() => new { LogMessage = Invariant($"Hangfire Server launched. Will terminate when there are no active jobs after: {timeout}.") }); // once the timeout has been achieved with no active jobs the process will exit (this assumes that a scheduled task will restart the process) // the main impetus for this was the fact that Hangfire won't reconnect correctly so we must periodically initiate an entire reconnect. while (activeMessageTracker.ActiveMessagesCount != 0 || (DateTime.UtcNow < timeout)) { Thread.Sleep(launchConfig.PollingInterval); } Log.Write(() => new { ex = Invariant($"Hangfire Server terminating. There are no active jobs and current time if beyond the timeout: {timeout}.") }); } }
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("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(); }
public void Start() { // Start code here... _backgroundJobServer = new BackgroundJobServer(); }
public void Start() { Configure(); //JobStorage.Current = new PostgreSqlStorage(_postgresStorageConnectionString); Server = new BackgroundJobServer(); }
private HangfireBootstrapper() { _backgroundJobServer = null; }
protected override void OnStart(string[] args) { _server = new BackgroundJobServer(); }
public void SetUp() { _backgroundJobServer = HangfireConfig.StartHangfire("TestHeyDb"); GlobalJobFilters.Filters.Add(new AutomaticRetryAttribute { Attempts = 0 }); _repository = new HangfireJobRepository(); var heyService = new HeyService(_repository); _heyController = new HeyController(heyService); _scheduledId = "1"; _scheduledHeyRemember = new HeyRememberDto() { Domain = "Hey.Api.Rest.Tests", Name = "GetTests", Id = _scheduledId, DomainSpecificData = "[]", When = new[] { DateTime.Now + TimeSpan.FromMinutes(60) } }; _processingId = "2"; _processingHeyRemember = new HeyRememberDto() { Domain = "Hey.Api.Rest.Tests", Name = "GetTests", Id = _processingId, DomainSpecificData = "[]", When = new[] { DateTime.Now } }; _succededId = "3"; _succededHeyRemember = new HeyRememberDto() { Domain = "Hey.Api.Rest.Tests", Name = "GetSuccessTests", Id = _succededId, DomainSpecificData = "[]", When = new[] { DateTime.Now } }; _failedId = "3"; _failedHeyRemember = new HeyRememberDto() { Domain = "Hey.Api.Rest.Tests", Name = "FailTests", Id = _failedId, DomainSpecificData = "[]", When = new[] { DateTime.Now } }; _recurringId = "4"; _recurringHeyRemember = new HeyRememberDto() { Domain = "Hey.Api.Rest.Tests", Name = "RecurringTests", Id = _recurringId, DomainSpecificData = "[]", When = new[] { DateTime.Today }, CronExpression = "* * * * *", }; }
public async Task StartHangfire() { backgroundJobServer = new BackgroundJobServer(); RecurringJob.AddOrUpdate(() => CheckForNotification(), Cron.MinuteInterval(5)); }
public HangFireScheduler(BackgroundJobServer backGroundJobServer, IScheduleCallback scheduleCallbacker) { this._hangfireValidationServer = Guard.NotNull(backGroundJobServer, "backGroundJobServer", log); this._sheduleCallbacker = Guard.NotNull(scheduleCallbacker, "scheduleCallbacker", log); }
public void Start() { _server = new BackgroundJobServer(); Log.Logger.Information(string.Format("##### :: Hangfire server started at: {0} :: #####", System.DateTime.UtcNow.ToString("dd MMM yyyy, hh:mm tt"))); }
public bool Start(HostControl hostControl) { _server = new BackgroundJobServer(); return(true); }
public static void Main() { LogManager.LogFactory = new ConsoleLogFactory(); RedisFactory.Host = "127.0.0.1:19999"; RedisFactory.Db = 3; GlobalJobFilters.Filters.Add(new HistoryStatisticsAttribute(), 20); GlobalJobFilters.Filters.Add(new RetryAttribute()); using (var server = new BackgroundJobServer(25, "critical", "default")) { server.Start(); 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("old", StringComparison.OrdinalIgnoreCase)) { var workCount = int.Parse(command.Substring(4)); for (var i = 0; i < workCount; i++) { Perform.Async <OldJob>(new { Hello = "world", Empty = (string)null, Number = 12.44 }); } } 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("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("recurring", StringComparison.OrdinalIgnoreCase)) { BackgroundJob.Enqueue <Services>(x => x.Recurring()); Console.WriteLine("Recurring job added"); } 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(); }
public void Start() { _jobServer = new BackgroundJobServer(); _manager = new RecurringJobManager(); }