コード例 #1
0
 private static WorkerHostBuilder AddSampleJobs(this WorkerHostBuilder workerHostBuilder)
 {
     workerHostBuilder.AddJob <LongRunningTaskJobHandler>()
     .WithScheduleTrigger("0 0/2 * * * ?", options => {
         options.Name        = "useless-task";
         options.Description = "Does nothing for some minutes.";
         options.Group       = "indice";
         options.Singleton   = true;
     })
     .AddJob <LoadAvailableAlertsJobHandler>()
     .WithScheduleTrigger <DemoCounterModel>("0 0/1 * * * ?", options => {
         options.Name        = "load-available-alerts";
         options.Description = "Load alerts for the queue.";
         options.Group       = "indice";
     })
     .AddJob <SendSmsJobHandler>()
     .WithQueueTrigger <SmsDto>(options => {
         options.QueueName       = "send-user-sms";
         options.PollingInterval = 500;
         options.InstanceCount   = 3;
     })
     .AddJob <LogSendSmsJobHandler>()
     .WithQueueTrigger <LogSmsDto>(options => {
         options.QueueName       = "log-send-user-sms";
         options.PollingInterval = 500;
         options.InstanceCount   = 1;
     });
     return(workerHostBuilder);
 }
コード例 #2
0
        public static WorkerHostBuilder UseFileLogging(this WorkerHostBuilder host, string logPath, string definedWorkerName)
        {
            // build the logfile name
            var workerName = String.Empty;

            if (String.IsNullOrEmpty(definedWorkerName))
            {
                workerName = String.Format("Worker-{0}-{1}", Environment.MachineName, Assembly.GetEntryAssembly().GetName().Name);
            }
            else
            {
                workerName = String.Format("Worker-{0}-{1}", Environment.MachineName, definedWorkerName);
            }

            // ensure the log path exists
            Directory.CreateDirectory(logPath);

            // add the logger
            var loggerFactory = host.Services.BuildServiceProvider().GetService <ILoggerFactory>();

            loggerFactory.AddFile(Path.Combine(logPath, workerName + "-{Date}.log"));

            // done
            return(host);
        }
コード例 #3
0
        public static WorkerHostBuilder UseConsoleLogging(this WorkerHostBuilder host)
        {
            var loggerFactory = host.Services.BuildServiceProvider().GetService <ILoggerFactory>();

            loggerFactory.AddConsole();
            return(host);
        }
コード例 #4
0
        public static WorkerHostBuilder UseFileLoggingInAppServices(this WorkerHostBuilder host)
        {
            // check if we are running in an Azure App Service
            if (!String.IsNullOrEmpty(Environment.GetEnvironmentVariable("APPSETTING_WEBSITE_SITE_NAME")))
            {
                // get the homePath
                string homePath = Environment.GetEnvironmentVariable("HOME");

                // use the assembly name directory
                var webjobName = Environment.GetEnvironmentVariable("WEBJOBS_NAME");
                if (String.IsNullOrEmpty(webjobName))
                {
                    string assemblyPath = Path.GetDirectoryName(Uri.UnescapeDataString(new UriBuilder(Assembly.GetEntryAssembly().CodeBase).Path));
                    var    pathPortions = assemblyPath.Split(Path.DirectorySeparatorChar);
                    webjobName = pathPortions[pathPortions.Length - 1];
                }

                // start logging on Azure WebSite
                return(host.UseFileLogging(Path.Combine(homePath, "LogFiles", "WebJobs"), webjobName));
            }
            else
            {
                // start logging on non Azure WebSite
                return(host.UseFileLogging(BuildLogPath(), String.Empty));
            }
        }
コード例 #5
0
        public static void Main(string[] args)
        {
            var host = new WorkerHostBuilder()
                       .UseConsoleLogging()
                       .UseFileLoggingInAppServices()
                       .UseStartup <Startup>()
                       .UseAzureAppServiceShutdownHandler()
                       .UsePolling(500)
                       .Build();

            host.Run(TimeSpan.Zero);
        }
コード例 #6
0
        /// <summary>
        /// Registers a hosted service that manages and configures the lifetime of background tasks.
        /// </summary>
        /// <param name="services">Specifies the contract for a collection of service descriptors.</param>
        /// <param name="configureAction">The delegate used to configure the worker host options.</param>
        /// <returns>The <see cref="WorkerHostBuilder"/> used to configure the worker host.</returns>
        public static WorkerHostBuilder AddWorkerHost(this IServiceCollection services, Action <WorkerHostOptions> configureAction = null)
        {
            var serviceProvider = services.BuildServiceProvider();
            var builderInstance = serviceProvider.GetService <WorkerHostBuilder>();

            if (builderInstance is not null)
            {
                return(builderInstance);
            }
            var workerHostOptions = new WorkerHostOptions(services)
            {
                ScheduledTaskStoreType = typeof(NoOpScheduledTaskStore <>),
                QueueStoreType         = typeof(NoOpMessageQueue <>),
                LockStoreType          = typeof(LockManagerNoop)
            };

            configureAction?.Invoke(workerHostOptions);
            services.AddSingleton(workerHostOptions.JsonOptions);
            var quartzConfiguration = new NameValueCollection {
                { "quartz.threadPool.maxConcurrency", "100" },
                { "quartz.threadPool.threadCount", "100" }
            };

            services.AddSingleton <ISchedulerFactory>(serviceProvider => new StdSchedulerFactory(quartzConfiguration));
            services.AddSingleton <IJobFactory, QuartzJobFactory>();
            services.AddTransient <QuartzJobRunner>();
            services.AddTransient <TaskHandlerActivator>();
            services.AddLockManagerNoop();
            var configuration = serviceProvider.GetRequiredService <IConfiguration>();

            if (!configuration.WorkerHostDisabled())
            {
                services.AddHostedService <WorkerHostedService>();
            }
            var builder = new WorkerHostBuilder(services, workerHostOptions);

            services.AddSingleton(builder);
            return(builder);
        }
コード例 #7
0
        /// <summary>
        /// Adds the job handlers required the for campaigns feature.
        /// </summary>
        /// <param name="workerHostBuilder">A helper class to configure the worker host.</param>
        /// <param name="configure"></param>
        /// <returns>The <see cref="WorkerHostBuilder"/> used to configure the worker host.</returns>
        public static WorkerHostBuilder AddCampaignsJobs(this WorkerHostBuilder workerHostBuilder, Action <CampaignsJobsOptions> configure = null)
        {
            var options = new CampaignsJobsOptions {
                Services = workerHostBuilder.Services
            };

            configure?.Invoke(options);
            options.Services = null;
            workerHostBuilder.Services.AddPlatformEventHandler <CampaignCreatedEvent, CampaignCreatedEventHandler>();
            workerHostBuilder.Services.TryAddTransient <Func <string, IPushNotificationService> >(serviceProvider => key => new PushNotificationServiceNoop());
            return(workerHostBuilder.AddJob <CampaignCreatedJobHandler>()
                   .WithQueueTrigger <CampaignQueueItem>(options => {
                options.QueueName = QueueNames.CampaignCreated;
                options.PollingInterval = TimeSpan.FromSeconds(30).TotalMilliseconds;
                options.InstanceCount = 1;
            })
                   .AddJob <SendPushNotificationJobHandler>()
                   .WithQueueTrigger <PushNotificationQueueItem>(options => {
                options.QueueName = QueueNames.SendPushNotification;
                options.PollingInterval = TimeSpan.FromSeconds(5).TotalMilliseconds;
                options.InstanceCount = 1;
            }));
        }
コード例 #8
0
 /// <summary>
 /// Registers a job that will be processed by the worker host. Usually followed by a <see cref="WithQueueTrigger{TWorkItem}(TaskTriggerBuilder, Action{QueueOptions})"/> call to configure the way that a job is triggered.
 /// </summary>
 /// <typeparam name="TJobHandler">The type of the class that will handle the job. Must have a process function.</typeparam>
 /// <param name="builder">The <see cref="WorkerHostBuilder"/> used to configure the worker host.</param>
 /// <returns>The <see cref="TaskTriggerBuilder"/> used to configure the way that a job is triggered.</returns>
 public static TaskTriggerBuilder AddJob <TJobHandler>(this WorkerHostBuilder builder) where TJobHandler : class => new(builder.Services, builder.Options, typeof(TJobHandler));