Run() public method

public Run ( IEnumerable task ) : void
task IEnumerable
return void
Exemplo n.º 1
0
        public void TestRunChainedWithFailures()
        {
            TaskRunner runner = new TaskRunner();

            runner.RunChained("Test0", "OK!!!", x =>
            {
                TaskRunner runner2 = new TaskRunner();
                runner.Run("Test1", "OK", y => y.FailUnless(2 + 2 != 4, "Erro"));
                runner.Run("Test2", "OK", y => y.FailUnless(false, "Erro"));
                runner.Run("Test3", "OK", y => y.FailUnless(!true, "Erro"));
                return(runner2.Results);
            });

            runner.Results.Count(x => x.ResultType == TaskRunner.Result.Type.Failure).Should().Be(3);
            runner.Results.Count(x => x.ResultTypeTag == "failure").Should().Be(3);
            runner.Results.Count(x => x.Message == "Erro").Should().Be(3);

            runner.Results.Count(x => x.ResultType == TaskRunner.Result.Type.Success).Should().Be(1);
            runner.Results.Count(x => x.ResultTypeTag == "success").Should().Be(1);
            runner.Results.Count(x => x.Message == "OK!!!").Should().Be(1);

            runner.Results.Count().Should().Be(4);
            runner.Results.Count(x => x.Description == "Test0").Should().Be(1);
            runner.Results.Count(x => x.Description == "Test1").Should().Be(1);
            runner.Results.Count(x => x.Description == "Test2").Should().Be(1);
            runner.Results.Count(x => x.Description == "Test3").Should().Be(1);
        }
Exemplo n.º 2
0
        public IList <TaskRunner.Result> Check()
        {
            TaskRunner runner = new TaskRunner();

            runner.Run("Database mapping", "Correctly mapped", x =>
                       new SchemaValidator(Simply.Do.GetNHibernateConfig()).Validate());

            runner.Run("Windows Service installed", "Installed",
                       x => x.WarnUnless(ServiceController.GetServices()
                                         .Any(y => y.ServiceName == Simply.Do.GetConfig <ApplicationConfig>().Service.Name), "Not installed"));


            return(new List <TaskRunner.Result>(runner.Results));
        }
Exemplo n.º 3
0
        public async Task <TaskResult> RunTaskAsync(string taskName)
        {
            context.Output
            .Append("Running Deploy-Task ", ConsoleColor.DarkCyan)
            .Append(taskName, ConsoleColor.Cyan)
            .Append(" on Agent ", ConsoleColor.DarkCyan)
            .Append(definition.Name, ConsoleColor.Cyan)
            .AppendLine("...", ConsoleColor.DarkCyan);

            var runner = new TaskRunner(messageClient, AgentSessionId);

            runner.OutputEvent += (o, e) => {
                context.Output.AppendRaw(e.Text);
            };

            Tasks.Add(runner);

            var result = await runner.Run(taskName);

            if (!result.Successful)
            {
                context.Output
                .AppendLine($"Deploy-Task '{taskName}' Failed!", ConsoleColor.Red)
                .AppendLine(result.Message, ConsoleColor.DarkYellow);
            }

            context.Output
            .Append("Deploy-Task ", ConsoleColor.DarkGreen)
            .Append(taskName, ConsoleColor.Green)
            .AppendLine(" completed successfully.", ConsoleColor.DarkGreen);

            return(result);
        }
Exemplo n.º 4
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ClientSocket" /> class.
        /// </summary>
        /// <param name="clientConfiguration">The client configuration.</param>
        /// <param name="endPoint">The end point to connect to.</param>
        /// <param name="host">The host name (required for SSL).</param>
        /// <param name="onError">Error callback.</param>
        /// <param name="version">Protocol version.</param>
        public ClientSocket(IgniteClientConfiguration clientConfiguration, EndPoint endPoint, string host,
                            Action onError = null, ClientProtocolVersion?version = null)
        {
            Debug.Assert(clientConfiguration != null);

            _onError = onError;
            _timeout = clientConfiguration.SocketTimeout;

            _socket = Connect(clientConfiguration, endPoint);
            _stream = GetSocketStream(_socket, clientConfiguration, host);

            ServerVersion = version ?? CurrentProtocolVersion;

            Validate(clientConfiguration);

            Handshake(clientConfiguration, ServerVersion);

            // Check periodically if any request has timed out.
            if (_timeout > TimeSpan.Zero)
            {
                // Minimum Socket timeout is 500ms.
                _timeoutCheckTimer = new Timer(CheckTimeouts, null, _timeout, TimeSpan.FromMilliseconds(500));
            }

            // Continuously and asynchronously wait for data from server.
            TaskRunner.Run(WaitForMessages);
        }
Exemplo n.º 5
0
 private static void ScheduleRespawn(Mob item)
 {
     if (item.SpawnPoint != null)
     {
         TaskRunner.Run(item.SpawnPoint.Spawn, TimeSpan.FromSeconds(15));
     }
 }
Exemplo n.º 6
0
        public async void RunDelete_SuccessAll()
        {
            _data.Clear();
            _data.AddRange(new List <JobTaskDefinitionDto>
            {
                new JobTaskDefinitionDto
                {
                    Id = 1, Name = "Delete Repository", Type = JobTaskDefinitionType.DeleteRepository, JobDefinitionId = 1, Sequence = 1
                },
                new JobTaskDefinitionDto
                {
                    Id = 2, Name = "Delete Hosting", Type = JobTaskDefinitionType.DeleteHosting, JobDefinitionId = 1, Sequence = 2
                }
            });

            _deleteRepositoryTask.Setup(t => t.RunMainTask(It.IsAny <Dictionary <string, string> >())).ReturnsAsync(new TaskRunnerResult(true, ""));
            _deleteHostingTask.Setup(t => t.RunMainTask(It.IsAny <Dictionary <string, string> >())).ReturnsAsync(new TaskRunnerResult(true, ""));

            var runner  = new TaskRunner(_jobTaskService, _jobQueueService.Object, _pluginManager.Object, _logger.Object);
            var results = await runner.Run(1, new JobDto { Id = 1, Code = "20180817.1", IsDeletion = true }, _data, Path.Combine(AppContext.BaseDirectory, "plugins"), "working");

            Assert.Equal(_data.Count, results.Count);
            Assert.True(results[1].IsSuccess);
            Assert.True(results[2].IsSuccess);

            _jobQueueService.Verify(j => j.UpdateJobQueue(1, It.Is <UpdateJobDto>(u => u.Status == JobStatus.Processing)), Times.Exactly(4));
        }
Exemplo n.º 7
0
        public void TestServerConnectionAborted()
        {
            var evt    = new ManualResetEventSlim();
            var ignite = Ignition.Start(TestUtils.GetTestConfiguration());

            var putGetTask = TaskRunner.Run(() =>
            {
                using (var client = StartClient())
                {
                    var cache = client.GetOrCreateCache <int, int>("foo");
                    evt.Set();

                    for (var i = 0; i < 100000; i++)
                    {
                        cache[i] = i;
                        Assert.AreEqual(i, cache.GetAsync(i).Result);
                    }
                }
            });

            evt.Wait();
            ignite.Dispose();

            var ex       = Assert.Throws <AggregateException>(() => putGetTask.Wait());
            var socketEx = ex.GetInnermostException() as SocketException;

            if (socketEx != null)
            {
                Assert.AreEqual(SocketError.ConnectionAborted, socketEx.SocketErrorCode);
            }
            else
            {
                Assert.Fail("Unexpected exception: " + ex);
            }
        }
Exemplo n.º 8
0
        protected Task Broadcast(Message message, Hash ignoredNodeId)
        {
            message.ToByteArray(true);

            lock (_lock)
            {
                foreach (var connection in _voteConnections)
                {
                    if (connection.NodeInfo.NodeId == ignoredNodeId)
                    {
                        continue;
                    }

                    try
                    {
                        TaskRunner.Run(() => connection.Send(message));
                    }
                    catch (Exception ex)
                    {
                        Log.IgnoreException(ex, this);
                    }
                }
            }

            return(Task.CompletedTask);
        }
Exemplo n.º 9
0
        public async Task RunTask()
        {
            if (HttpContext.WebSockets.IsWebSocketRequest)
            {
                var webSocket = await HttpContext.WebSockets.AcceptWebSocketAsync();

                var buffer = new byte[1024 * 4];
                var result = await webSocket.ReceiveAsync(
                    new ArraySegment <byte>(buffer), CancellationToken.None);

                var runner = new TaskRunner(webSocket);

                while (!result.CloseStatus.HasValue)
                {
                    var msg = Encoding.UTF8.GetString(buffer).TrimEnd('\0');
                    if (msg == null)
                    {
                        continue;
                    }

                    await runner.Run(msg);

                    result = await webSocket.ReceiveAsync(
                        new ArraySegment <byte>(buffer), CancellationToken.None);
                }
                await webSocket.CloseAsync(result.CloseStatus.Value, result.CloseStatusDescription, CancellationToken.None);
            }
        }
Exemplo n.º 10
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ClientSocket" /> class.
        /// </summary>
        /// <param name="clientConfiguration">The client configuration.</param>
        /// <param name="endPoint">The end point to connect to.</param>
        /// <param name="host">The host name (required for SSL).</param>
        /// <param name="version">Protocol version.</param>
        /// <param name="topVerCallback">Topology version update callback.</param>
        public ClientSocket(IgniteClientConfiguration clientConfiguration, EndPoint endPoint, string host,
                            ClientProtocolVersion?version = null,
                            Action <AffinityTopologyVersion> topVerCallback = null)
        {
            Debug.Assert(clientConfiguration != null);

            _topVerCallback = topVerCallback;
            _timeout        = clientConfiguration.SocketTimeout;

            _socket = Connect(clientConfiguration, endPoint);
            _stream = GetSocketStream(_socket, clientConfiguration, host);

            ServerVersion = version ?? CurrentProtocolVersion;

            Validate(clientConfiguration);

            Handshake(clientConfiguration, ServerVersion);

            // Check periodically if any request has timed out.
            if (_timeout > TimeSpan.Zero)
            {
                // Minimum Socket timeout is 500ms.
                _timeoutCheckTimer = new Timer(CheckTimeouts, null, _timeout, TimeSpan.FromMilliseconds(500));
            }

            // Continuously and asynchronously wait for data from server.
            // TaskCreationOptions.LongRunning actually means a new thread.
            TaskRunner.Run(WaitForMessages, TaskCreationOptions.LongRunning);
        }
Exemplo n.º 11
0
        private static void Main(string[] args)
        {
            var taskIO     = new TaskIO();
            var runProgram = new TaskRunner(taskIO);

            runProgram.Run();
        }
Exemplo n.º 12
0
        public Task <bool> Start()
        {
            if (_started)
            {
                Log.Error("Node discovery already startet.", this);
                return(Task.FromResult(false));
            }
            _started = true;

            Log.Info($"Starting node discovery with node id {LocalId.HexString}.", this);
            Log.Info($"Node key is {LocalKey.PublicKey.HexString}.", this);
            Log.Info($"Network key is {NetworkKey.HexString}.", this);

            TaskRunner.Run(async() =>
            {
                var beacons = NodeConfiguration.AutoConnectNodes.Concat(NodeConfiguration.BeaconNodes);
                if (beacons != null)
                {
                    foreach (var endpoint in beacons)
                    {
                        await QueryEndPoint(endpoint, true);
                    }
                }
            });

            TaskRunner.Run(() => DiscoveryLoop());
            TaskRunner.Run(() => PingOldestLoop());
            TaskRunner.Run(() => QueryLoop());

            return(Task.FromResult(true));
        }
Exemplo n.º 13
0
        public void TestAllTasksSuccessful()
        {
            TaskRunner runner = new TaskRunner();

            runner.Run("Test1", "OK", x => x.FailUnless(2 + 2 == 4, "Erro"));
            runner.Run("Test2", "OK", x => x.FailUnless(true, "Erro"));
            runner.Run("Test3", "OK", x => x.FailUnless(!false, "Erro"));

            runner.Results.Count(x => x.ResultType == TaskRunner.Result.Type.Success).Should().Be(3);
            runner.Results.Count(x => x.ResultTypeTag == "success").Should().Be(3);
            runner.Results.Count(x => x.Message == "OK").Should().Be(3);

            runner.Results.Count().Should().Be(3);
            runner.Results.Count(x => x.Description == "Test1").Should().Be(1);
            runner.Results.Count(x => x.Description == "Test2").Should().Be(1);
            runner.Results.Count(x => x.Description == "Test3").Should().Be(1);
        }
Exemplo n.º 14
0
        public void TestAllFailedTaskByFailUnless()
        {
            TaskRunner runner = new TaskRunner();

            runner.Run("Test1", "OK", x => x.FailUnless(false, "OKOK"));
            runner.Run("Test2", "OK", x => x.FailUnless(false, "OKOK"));
            runner.Run("Test3", "OK", x => x.FailUnless(false, "OKOK"));

            runner.Results.Count(x => x.ResultType == TaskRunner.Result.Type.Failure).Should().Be(3);
            runner.Results.Count(x => x.ResultTypeTag == "failure").Should().Be(3);
            runner.Results.Count(x => x.Message == "OKOK").Should().Be(3);

            runner.Results.Count().Should().Be(3);
            runner.Results.Count(x => x.Description == "Test1").Should().Be(1);
            runner.Results.Count(x => x.Description == "Test2").Should().Be(1);
            runner.Results.Count(x => x.Description == "Test3").Should().Be(1);
        }
Exemplo n.º 15
0
 void runTask(ITestTask task)
 {
     var taskRunner = new TaskRunner();
     var runResult = taskRunner.Run(task);
     // 20150112
     // task.TaskFinished = true
     task.TaskStatus = runResult ? TestTaskStatuses.CompletedSuccessfully : TestTaskStatuses.Interrupted;
 }
Exemplo n.º 16
0
        public override void HandlePacket(PacketReader packet, GameClient client)
        {
            var channel = packet.ReadByte();

            client.ChangeChannel(channel);

            TaskRunner.Run(() => client.Terminate($"Changing Channels: {client.Server.ChannelId} -> {channel}"), TimeSpan.FromSeconds(5));
        }
Exemplo n.º 17
0
        public void TestAllFailedTaskByException()
        {
            TaskRunner runner = new TaskRunner();

            runner.Run("Test1", "OK", x => { throw new Exception("Whatever"); });
            runner.Run("Test2", "OK", x => { throw new Exception("Whatever"); });
            runner.Run("Test3", "OK", x => { throw new Exception("Whatever"); });

            runner.Results.Count(x => x.ResultType == TaskRunner.Result.Type.Failure).Should().Be(3);
            runner.Results.Count(x => x.ResultTypeTag == "failure").Should().Be(3);
            runner.Results.Count(x => x.Message == "Whatever").Should().Be(3);

            runner.Results.Count().Should().Be(3);
            runner.Results.Count(x => x.Description == "Test1").Should().Be(1);
            runner.Results.Count(x => x.Description == "Test2").Should().Be(1);
            runner.Results.Count(x => x.Description == "Test3").Should().Be(1);
        }
Exemplo n.º 18
0
        public async Task Connect(NodeInfo nodeInfo, Uri endPoint = null)
        {
            if (_node.HasQuit)
            {
                return;
            }

            if (nodeInfo == null)
            {
                return;
            }

            var accept = false;

            lock (_lock)
                accept = _outgoingConnections.Count <= _maxOutgoingConnections;

            if (!accept)
            {
                return;
            }

            if (IsConnected(nodeInfo, true))
            {
                return;
            }

            if (endPoint == null)
            {
                endPoint = nodeInfo.PublicEndPoint;
            }

            var client = new NodeClient(endPoint);

            var connection = await client.OpenNodeConnection();

            if (connection.Connected)
            {
                if (Log.LogTrace)
                {
                    Log.Trace($"NodeServer ({_kademlia.LocalNodeInfo.PublicEndPoint}) connecting {nodeInfo.PublicEndPoint}");
                }

                connection.NodeInfo              = nodeInfo;
                connection.OutgoingConnection    = true;
                connection.ConnectionClosedEvent = ConnectionClosed;
                connection.ConnectionList        = _pendingConnections;

                lock (_lock)
                    _pendingConnections.Add(connection);

                TaskRunner.Run(() => connection.Receive(this));

                await connection.Send(new NodeInfoMessage(_kademlia.NodeConfiguration, nodeInfo.NodeId) { SignKey = _kademlia.LocalKey });
            }
        }
Exemplo n.º 19
0
        public override Task <bool> OpenAsync()
        {
            CheckWasDisposed();

            return(TaskRunner.Run <bool>(() =>
            {
                Open();
                return true;
            }));
        }
Exemplo n.º 20
0
 public override void When()
 {
     _runner = new TaskRunner(_someKey, _getTaskFunc, _someSpinInterval, HandleExceptionFunc, _cancellationTokenSource.Token);
     _result = _runner.Run();
     Task.Delay(GetTimeoutFor(expectedExecutionTimes: 5, interval: _someSpinInterval)).Wait();
     _runner.Stop();
     _processException = Catch.Exception(() =>
                                         _result.Wait()
                                         );
 }
Exemplo n.º 21
0
 public void ScheduleExpiration()
 {
     TaskRunner.Run(() =>
     {
         if (Parent.Summons.Contains(MapleId))
         {
             Parent.Summons.Remove(this);
         }
     }, TimeSpan.FromMilliseconds((Expiration - DateTime.UtcNow).TotalMilliseconds));
 }
Exemplo n.º 22
0
        public void TestRemoteListenMultithreaded()
        {
            const int threadCnt  = 20;
            const int runSeconds = 20;

            var messaging = _grid1.GetMessaging();

            var senders = TaskRunner.Run(() => TestUtils.RunMultiThreaded(() =>
            {
                MessagingTestHelper.ClearReceived(int.MaxValue);
                messaging.Send(NextMessage());
                Thread.Sleep(50);
            }, threadCnt, runSeconds));


            var sharedListener = MessagingTestHelper.GetListener();

            for (int i = 0; i < 100; i++)
            {
                messaging.RemoteListen(sharedListener);  // add some listeners to be stopped by filter result
            }
            TestUtils.RunMultiThreaded(() =>
            {
                // Check that listen/stop work concurrently
                messaging.StopRemoteListen(messaging.RemoteListen(sharedListener));
            }, threadCnt, runSeconds / 2);

            MessagingTestHelper.ListenResult = false;

            messaging.Send(NextMessage());                  // send a message to make filters return false

            Thread.Sleep(MessagingTestHelper.SleepTimeout); // wait for all to unsubscribe

            MessagingTestHelper.ListenResult = true;

            senders.Wait(); // wait for senders to stop

            MessagingTestHelper.ClearReceived(int.MaxValue);

            var lastMsg = NextMessage();

            messaging.Send(lastMsg);

            Thread.Sleep(MessagingTestHelper.SleepTimeout);

            // Check that unsubscription worked properly
            var sharedResult = MessagingTestHelper.ReceivedMessages.ToArray();

            if (sharedResult.Length != 0)
            {
                Assert.Fail("Unexpected messages ({0}): {1}; last sent message: {2}", sharedResult.Length,
                            string.Join(",", sharedResult), lastMsg);
            }
        }
Exemplo n.º 23
0
        public override void HandlePacket(PacketReader packet, GameClient client)
        {
            if (client.GameCharacter.Map.CachedReference.IsUnableToShop)
            {
                Portal.SendMapTransferResult(client.GameCharacter, MapTransferResult.CannotGo);
                return;
            }

            client.OpenCashShop();
            TaskRunner.Run(() => client.Terminate("Migrating to Cash Shop"), TimeSpan.FromSeconds(5));
        }
        public void TestTxDeadlockDetection()
        {
            if (LocalCache())
            {
                return;
            }

            var cache = Cache();

            var keys0 = Enumerable.Range(1, 100).ToArray();

            cache.PutAll(keys0.ToDictionary(x => x, x => x));

            var barrier = new Barrier(2);

            Action <int[]> increment = keys =>
            {
                using (var tx = Transactions.TxStart(TransactionConcurrency.Pessimistic,
                                                     TransactionIsolation.RepeatableRead, TimeSpan.FromSeconds(0.5), 0))
                {
                    foreach (var key in keys)
                    {
                        cache[key]++;
                    }

                    barrier.SignalAndWait(500);

                    tx.Commit();
                }
            };

            // Increment keys within tx in different order to cause a deadlock.
            var aex = Assert.Throws <AggregateException>(() =>
                                                         Task.WaitAll(new[]
            {
                TaskRunner.Run(() => increment(keys0)),
                TaskRunner.Run(() => increment(keys0.Reverse().ToArray()))
            },
                                                                      TimeSpan.FromSeconds(40)));

            Assert.AreEqual(2, aex.InnerExceptions.Count);

            var deadlockEx = aex.InnerExceptions.OfType <TransactionDeadlockException>().FirstOrDefault();

            if (deadlockEx != null)
            {
                Assert.IsTrue(deadlockEx.Message.Trim().StartsWith("Deadlock detected:"), deadlockEx.Message);
            }
            else
            {
                Assert.Fail("Unexpected exception: " + aex);
            }
        }
Exemplo n.º 25
0
        public void Execute_Timing()
        {
            int        expected = 3;
            int        actual   = 0;
            TaskRunner runner   = new TaskRunner("", () => actual = expected);

            actual.Should().Equals(0);

            runner.Run();

            actual.Should().Equals(expected);
        }
Exemplo n.º 26
0
        public void TestOneWarnedTask()
        {
            TaskRunner runner = new TaskRunner();

            runner.Run("Test1", "OK", x => x.FailUnless(2 + 2 == 4, "Erro"));
            runner.Run("Test2", "OK", x => x.WarnUnless(false, "Warn"));
            runner.Run("Test3", "OK", x => x.FailUnless(!false, "Erro"));

            runner.Results.Count(x => x.ResultType == TaskRunner.Result.Type.Success).Should().Be(2);
            runner.Results.Count(x => x.ResultTypeTag == "success").Should().Be(2);
            runner.Results.Count(x => x.Message == "OK").Should().Be(2);

            runner.Results.Count(x => x.ResultType == TaskRunner.Result.Type.Warning).Should().Be(1);
            runner.Results.Count(x => x.ResultTypeTag == "warning").Should().Be(1);
            runner.Results.Count(x => x.Message == "Warn").Should().Be(1);

            runner.Results.Count().Should().Be(3);
            runner.Results.Count(x => x.Description == "Test1").Should().Be(1);
            runner.Results.Count(x => x.Description == "Test2").Should().Be(1);
            runner.Results.Count(x => x.Description == "Test3").Should().Be(1);
        }
Exemplo n.º 27
0
        public void TestOneFailedTaskByException()
        {
            TaskRunner runner = new TaskRunner();

            runner.Run("Test1", "OK", x => x.FailUnless(2 + 2 == 4, "Erro"));
            runner.Run("Test2", "OK", x => { throw new Exception("Whatever"); });
            runner.Run("Test3", "OK", x => x.FailUnless(!false, "Erro"));

            runner.Results.Count(x => x.ResultType == TaskRunner.Result.Type.Success).Should().Be(2);
            runner.Results.Count(x => x.ResultTypeTag == "success").Should().Be(2);
            runner.Results.Count(x => x.Message == "OK").Should().Be(2);

            runner.Results.Count(x => x.ResultType == TaskRunner.Result.Type.Failure).Should().Be(1);
            runner.Results.Count(x => x.ResultTypeTag == "failure").Should().Be(1);
            runner.Results.Count(x => x.Message == "Whatever").Should().Be(1);

            runner.Results.Count().Should().Be(3);
            runner.Results.Count(x => x.Description == "Test1").Should().Be(1);
            runner.Results.Count(x => x.Description == "Test2").Should().Be(1);
            runner.Results.Count(x => x.Description == "Test3").Should().Be(1);
        }
Exemplo n.º 28
0
        public async void Run_SuccessOne_PendingTheNext()
        {
            _data.Clear();

            _data.AddRange(new List <JobTaskDefinitionDto>
            {
                new JobTaskDefinitionDto
                {
                    Id = 1, Name = "Generate web app", Type = JobTaskDefinitionType.Generate, JobDefinitionId = 1, Sequence = 1
                },
                new JobTaskDefinitionDto
                {
                    Id = 2, Name = "Push code to GitHub", Type = JobTaskDefinitionType.Push, JobDefinitionId = 1, Sequence = 2, Configs = new Dictionary <string, string>
                    {
                        { "CreatePullRequest", "true" }
                    }
                },
                new JobTaskDefinitionDto
                {
                    Id = 3, Name = "Merge PR to GitHub", Type = JobTaskDefinitionType.Push, JobDefinitionId = 1, Sequence = 3
                },
                new JobTaskDefinitionDto
                {
                    Id = 4, Name = "Build web app", Type = JobTaskDefinitionType.Build, JobDefinitionId = 1, Sequence = 4
                },
                new JobTaskDefinitionDto
                {
                    Id = 5, Name = "Deploy web app", Type = JobTaskDefinitionType.Deploy, JobDefinitionId = 1, Sequence = 5
                }
            });

            _generateTask.Setup(t => t.RunMainTask(It.IsAny <Dictionary <string, string> >())).ReturnsAsync(new TaskRunnerResult(true, ""));
            _pushTask.Setup(t => t.RunMainTask(It.IsAny <Dictionary <string, string> >())).ReturnsAsync(new TaskRunnerResult(true, "", true));

            var job = new JobDto {
                Id = 1, Code = "20180817.1"
            };
            var runner  = new TaskRunner(_jobTaskService, _jobQueueService.Object, _pluginManager.Object, _logger.Object);
            var results = await runner.Run(1, job, _data, Path.Combine(AppContext.BaseDirectory, "plugins"), "working");

            Assert.Equal(_data.Count, results.Count);
            Assert.True(results[1].IsSuccess);
            Assert.True(results[2].IsSuccess);
            Assert.True(results[2].StopTheProcess);
            Assert.False(results[3].IsProcessed);
            Assert.False(results[4].IsProcessed);
            Assert.False(results[5].IsProcessed);

            Assert.Contains(job.JobTasksStatus, j => j.Status == JobTaskStatusType.Pending);
        }
Exemplo n.º 29
0
 private async void ShowModalProgress(object sender, RoutedEventArgs e)
 {
     await TaskRunner.Run(async controller =>
     {
         for (var i = 1; i <= 100; i++)
         {
             controller.Progress = i;
             await Task.Delay(50);
         }
     }, new ProgressDialogOptions
     {
         Message = "Processing data..."
     }, "RootDialog");
 }
Exemplo n.º 30
0
        private void ScheduleExpiration(Drop item)
        {
            item.Expiry?.Cancel();
            item.Expiry?.Dispose();

            item.Expiry = TaskRunner.Run(() =>
            {
                if (item.Map == Map)
                {
                    item.Picker = null;
                    Remove(item);
                }
            }, TimeSpan.FromMilliseconds(Drop.ExpiryTime));
        }
Exemplo n.º 31
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ClientSocket" /> class.
        /// </summary>
        /// <param name="clientConfiguration">The client configuration.</param>
        /// <param name="endPoint">The end point to connect to.</param>
        /// <param name="host">The host name (required for SSL).</param>
        /// <param name="version">Protocol version.</param>
        /// <param name="topVerCallback">Topology version update callback.</param>
        /// <param name="marshaller">Marshaller.</param>
        public ClientSocket(IgniteClientConfiguration clientConfiguration, EndPoint endPoint, string host,
                            ClientProtocolVersion?version, Action <AffinityTopologyVersion> topVerCallback,
                            Marshaller marshaller)
        {
            Debug.Assert(clientConfiguration != null);
            Debug.Assert(endPoint != null);
            Debug.Assert(!string.IsNullOrWhiteSpace(host));
            Debug.Assert(topVerCallback != null);
            Debug.Assert(marshaller != null);

            _topVerCallback = topVerCallback;
            _marsh          = marshaller;
            _timeout        = clientConfiguration.SocketTimeout;
            _logger         = (clientConfiguration.Logger ?? NoopLogger.Instance).GetLogger(GetType());

            _socket = Connect(clientConfiguration, endPoint, _logger);
            _stream = GetSocketStream(_socket, clientConfiguration, host);

            ServerVersion = version ?? CurrentProtocolVersion;

            Validate(clientConfiguration);

            _features = Handshake(clientConfiguration, ServerVersion);

            if (clientConfiguration.EnableHeartbeats)
            {
                if (_features.HasFeature(ClientBitmaskFeature.Heartbeat))
                {
                    _heartbeatInterval = GetHeartbeatInterval(clientConfiguration);

                    _heartbeatTimer = new Timer(SendHeartbeat, null, dueTime: _heartbeatInterval,
                                                period: TimeSpan.FromMilliseconds(-1));
                }
                else
                {
                    _logger.Warn("Heartbeats are enabled, but server does not support heartbeat feature.");
                }
            }

            // Check periodically if any request has timed out.
            if (_timeout > TimeSpan.Zero)
            {
                // Minimum Socket timeout is 500ms.
                _timeoutCheckTimer = new Timer(CheckTimeouts, null, _timeout, TimeSpan.FromMilliseconds(500));
            }

            // Continuously and asynchronously wait for data from server.
            // TaskCreationOptions.LongRunning actually means a new thread.
            TaskRunner.Run(WaitForMessages, TaskCreationOptions.LongRunning);
        }
Exemplo n.º 32
0
        protected override void OnPageEnter_Finishing()
        {
            // OK button does Cancel until processing finished.
            Wizard.OKButtonText = Translator.Translate("TXT_CANCEL");
            Wizard.ShowRepeatWizard = false;
            Wizard.ShowMovementButtons = false;
            Wizard.ShowOKButton = true;

            lblWizardResults.Text = Translator.Translate("TXT_WIZTASKSRUNNING");

            _errorsFound = false;
            tvResults.Visible = _errorsFound;

            // Execute wizard
            if (BkgTask != null)
            {
                BkgTask.Reset();

                // Resubscribe for task events
                BkgTask.TaskProgress -= new TaskProgressHandler(task_TaskProgress);
                BkgTask.TaskFinished -= new TaskFinishedHandler(task_TaskFinished);
                BkgTask.TaskStepInit -= new TaskStepInitHandler(task_TaskStepInit);

                BkgTask.TaskProgress += new TaskProgressHandler(task_TaskProgress);
                BkgTask.TaskFinished += new TaskFinishedHandler(task_TaskFinished);
                BkgTask.TaskStepInit += new TaskStepInitHandler(task_TaskStepInit);

                tvResults.Nodes.Clear();

                pbProgress.Visible = true;
                pbProgress.Value = 0;

                if (BkgTask.TotalSteps > 1)
                {
                    pbProgress.Maximum = BkgTask.TotalSteps;
                    //pbProgress.Style = ProgressBarStyle.Continuous;
                }
                else
                {
                    pbProgress.Maximum = 1;
                    //pbProgress.Style = ProgressBarStyle.Marquee;
                }

                _runner = new TaskRunner(BkgTask);
                _runner.Run();
            }
        }