예제 #1
0
        public Task Create(BackgroundServerContext context, CancellationToken token)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            return(Task.Factory.StartNew(() =>
            {
                var workerContext = new BackgroundWorkerContext(context.Console);

                while (!token.IsCancellationRequested)
                {
                    BackgroundWorkerContinuation continuation = _worker.Work(workerContext.Increment(), token);

                    TimeSpan waitTime = continuation.WaitTime.GetValueOrDefault();

                    if (waitTime <= TimeSpan.Zero)
                    {
                        break;
                    }

                    token.WaitHandle.WaitOne(waitTime);
                }
            }, token, TaskCreationOptions.LongRunning, _scheduler));
        }
            public BackgroundWorkerContinuation Work(BackgroundWorkerContext context, CancellationToken token)
            {
                _writer.WriteLine("Adding message");
                _queue.Add(_factory.Message);

                return(context.Exit());
            }
        public BackgroundWorkerContinuation Work(BackgroundWorkerContext context, CancellationToken token)
        {
            context.Console.WriteLine($"Sending message from Worker {context.InvocationCount}");

            _bus.Send($"Hello {context.InvocationCount}").Wait(token);

            return(context.Wait(TimeSpan.FromSeconds(5)));
        }
예제 #4
0
            public BackgroundWorkerContinuation Work(BackgroundWorkerContext context, CancellationToken token)
            {
                Request(context, token, "hello");
                Request(context, token, "custom/url/route");
                Request(context, token, "custom/url/route/different");

                return(context.Wait(TimeSpan.FromSeconds(5)));
            }
예제 #5
0
        public BackgroundWorkerContinuation Work(BackgroundWorkerContext context, CancellationToken token)
        {
            if (context.InvocationCount == 10)
            {
                return(context.Exit());
            }

            return(context.Wait(TimeSpan.FromSeconds(1)));
        }
예제 #6
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="workerContext"></param>
        /// <returns></returns>
        protected override async Task DoWorkAsync(BackgroundWorkerContext workerContext)
        {
            var store = workerContext.ServiceProvider.GetRequiredService <IBackgroundJobStore>();

            var waitingJobs = await store.GetWaitingJobsAsync(WorkerOptions.MaxJobFetchCount);

            if (!waitingJobs.Any())
            {
                return;
            }

            var jobExecuter = workerContext.ServiceProvider.GetRequiredService <IBackgroundJobExecuter>();
            var clock       = workerContext.ServiceProvider.GetRequiredService <IClock>();
            var serializer  = workerContext.ServiceProvider.GetRequiredService <IBackgroundJobSerializer>();

            foreach (var jobInfo in waitingJobs)
            {
                jobInfo.TryCount++;
                jobInfo.LastTryTime = clock.Now;

                try
                {
                    var jobConfiguration = JobOptions.GetJob(jobInfo.JobName);
                    var jobArgs          = serializer.Deserialize(jobInfo.JobArgs, jobConfiguration.ArgsType);
                    var context          = new JobExecutionContext(workerContext.ServiceProvider, jobConfiguration.JobType, jobArgs);

                    try
                    {
                        await jobExecuter.ExecuteAsync(context);

                        await store.DeleteAsync(jobInfo.Id);
                    }
                    catch (BackgroundJobExecutionException)
                    {
                        var nextTryTime = CalculateNextTryTime(jobInfo, clock);

                        if (nextTryTime.HasValue)
                        {
                            jobInfo.NextTryTime = nextTryTime.Value;
                        }
                        else
                        {
                            jobInfo.IsAbandoned = true;
                        }

                        await TryUpdateAsync(store, jobInfo);
                    }
                }
                catch (Exception ex)
                {
                    Logger.LogException(ex);
                    jobInfo.IsAbandoned = true;
                    await TryUpdateAsync(store, jobInfo);
                }
            }
        }
예제 #7
0
            private void Request(BackgroundWorkerContext context, CancellationToken token, string path)
            {
                string url = $"{_webApiUrl}/{path}";

                context.Console.WriteLine("[HttpGet]: {0}", url);

                using (HttpResponseMessage hello = _httpClient.GetAsync(url, token).Result)
                {
                    context.Console.WriteLine($" => {hello.Content.ReadAsStringAsync().Result}");
                }
            }
예제 #8
0
        public BackgroundWorkerContinuation Work(BackgroundWorkerContext context, CancellationToken token)
        {
            if (context.InvocationCount < 5u)
            {
                throw new InvalidOperationException();
            }

            context.Console.WriteLine($"{nameof(MyOtherWorker)}: Invocation#: {context.InvocationCount}");

            return(context.Wait(TimeSpan.FromSeconds(2)));
        }
예제 #9
0
        public BackgroundWorkerContinuation Work(BackgroundWorkerContext context, CancellationToken token)
        {
            var message = $"A message from the \"Fire and forget\"-worker (#{context.InvocationCount}) - containing {{json}}";

            BackgroundJob.Enqueue <IHangfireJob>(x => x.WriteMessageToTheConsoleWriter(message));

            const string anotherMessage = "A different message from the \"Fire and forget\"-worker (#{0}) - containing string format";

            BackgroundJob.Enqueue <IHangfireJob>(x => x.WriteMessageToTheConsoleWriter(anotherMessage, context.InvocationCount));

            return(context.Wait(TimeSpan.FromSeconds(10)));
        }
예제 #10
0
        public BackgroundWorkerContinuation Work(BackgroundWorkerContext context, CancellationToken token)
        {
            var logEntry = new HeartbeatLogEntry(Time.UtcNow);

            foreach (IHeartbeatProvider provider in _providers)
            {
                logEntry.CollectFrom(provider, token);
            }

            _repository.Insert(logEntry);

            return(context.Wait(_interval));
        }
예제 #11
0
        public BackgroundWorkerContinuation Work(BackgroundWorkerContext context, CancellationToken token)
        {
            if (token.IsCancellationRequested)
            {
                return(context.Exit());
            }

            if (context.InvocationCount == 1)
            {
                foreach (BackgroundServerHost host in _servers)
                {
                    try
                    {
                        host.Start();

                        _isRunning.Add(host);
                    }
                    catch (Exception ex)
                    {
                        LogError(host, ex);
                    }
                }

                _output($"Started {_isRunning.Count} server(s)");

                return(context.Wait(_configuration.HouseKeepingInterval));
            }

            // Calculates whether to output status text or not, depending on number of iterations.
            bool outputStatus = _configuration.OutputStatusText(context.InvocationCount);

            CheckIsRunning(outputStatus);

            if (ExitHouseKeeping())
            {
                _output("Exiting (no more servers left to monitor)");

                Dispose();
                return(context.Exit());
            }

            if (outputStatus)
            {
                _output($"{_isRunning.Count} server(s) running. Uptime: {_uptime.GetUptimeText(_startedAt)}");
            }

            return(context.Wait(_configuration.HouseKeepingInterval));
        }
예제 #12
0
        public BackgroundWorkerContinuation Work(BackgroundWorkerContext context, CancellationToken token)
        {
            //BackgroundJob.Enqueue<ISomeInterfaceMissingImplementation>(x => x.CallMeAndHangfireWillThrowException());

            return(context.Wait(TimeSpan.FromSeconds(7)));
        }
예제 #13
0
        public BackgroundWorkerContinuation Work(BackgroundWorkerContext context, CancellationToken token)
        {
            context.Console.WriteLine($"Hello #{context.InvocationCount}");

            return(context.Wait(TimeSpan.FromSeconds(10)));
        }
예제 #14
0
            public BackgroundWorkerContinuation Work(BackgroundWorkerContext context, CancellationToken token)
            {
                _bus.SendLocal(_message).Wait(token);

                return(context.Exit());
            }
 public BackgroundWorkerContinuation Work(BackgroundWorkerContext context, CancellationToken token)
 {
     _waitBlock.Release();
     throw new WorkException();
 }
 public BackgroundWorkerContinuation Work(BackgroundWorkerContext context, CancellationToken token)
 {
     throw new WorkException();
 }
예제 #17
0
        public BackgroundWorkerContinuation Work(BackgroundWorkerContext context, CancellationToken token)
        {
            context.Console.WriteLine($"{nameof(MyOtherWorker)}: Invocation#: {context.InvocationCount}");

            return(context.Wait(TimeSpan.FromSeconds(2)));
        }